用PHP中的eval和_调用定义getter/setter方法
我提供的代码没有意义,因为我以一种易于测试的方式进行了编辑 顺便说一句,在我的例子中,ParentClass是数据库类,setter/getter方法用于选择和更新表字段用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
<?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添加了数组短语法