我有一个函数,它应该读取数组并动态设置对象属性。
class A {
public $a;
public $b;
function set($array){
foreach ($array as $key => $value){
if ( property_exists ( $this , $key ) ){
$this->{$key} = $value;
}
}
}
}
$a = new A();
$val = Array( "a" => "this should be set to property", "b" => "and this also");
$a->set($val);
嗯,显然是行不通的,有没有办法做到这一点?
编辑
这段代码好像没什么问题,应该关题了
最佳答案
您只需删除括号 {} 即可! -> $this->$key = $value;
关于PHP 动态设置对象属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21336747/