Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/292.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ionic-framework/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
用PHP中的eval和_调用定义getter/setter方法_Php_Eval_Setter_Getter - Fatal编程技术网

用PHP中的eval和_调用定义getter/setter方法

用PHP中的eval和_调用定义getter/setter方法,php,eval,setter,getter,Php,Eval,Setter,Getter,我提供的代码没有意义,因为我以一种易于测试的方式进行了编辑 顺便说一句,在我的例子中,ParentClass是数据库类,setter/getter方法用于选择和更新表字段 <?php abstract class ParentClass { protected static $properties = [] ; public function __construct() { foreach (static::$properties as

我提供的代码没有意义,因为我以一种易于测试的方式进行了编辑

顺便说一句,在我的例子中,ParentClass是数据库类,setter/getter方法用于选择和更新表字段

<?php

abstract class ParentClass {

    protected static
    $properties = []
    ;

    public function __construct() {
        foreach (static::$properties as $property) {
            $setterName = "Set".ucfirst($property);
            $this->$setterName = eval('function($value){$this->'.$property.' = $value;};');
            $getterName = "Get".ucfirst($property);
            $this->$getterName = eval('function(){return $this->'.$property.';};');
        }
    }

    public function __call($method, $args) {
        if (isset($this->$method)) {
            $func = $this->$method;
            return call_user_func_array($func, $args);
        }
    }

}

class ChildClass extends ParentClass {

    protected static
    $properties = [
        "property1"
    ]
    ;

    protected
    $property1
    ;

}

$childClass = new ChildClass();
$childClass->SetProperty1("value");
echo $childClass->GetProperty1();

?>

脚本的输出为空

我缺少什么?

返回
NULL
,除非
返回
eval
ed代码中的某个地方。当前,当您设置
$this->$setterName
时,您的
eval
实际做的是创建一个闭包,然后将其丢弃(因为它没有被其他方式使用),返回
NULL
,最后得到
$this->SetProperty1=NULL

相反,您应该直接使用闭包:

public function __construct() {
    foreach (static::$properties as $property) {
        $setterName = "Set".ucfirst($property);
        $this->$setterName = function($value) use($property) {$this->$property = $value;};
        $getterName = "Get".ucfirst($property);
        $this->$getterName = function() use($property) {return $this->$property;};
    }
}

您使用的是什么版本的PHP?5.4添加了数组短语法