在 PHP 中使用 eval 和 __call 定义 getter/setter 方法


Define getter/setter methods with eval and __call in PHP

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

顺便说一句,在我的例子中,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();
?>

脚本的输出什么都没有。

我错过了什么?

>eval返回NULL,除非returneval 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;};
    }
}