我有一个函数,应该读取数组并动态设置对象属性.
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);
好吧,显然这是行不通的,有没有办法做到这一点?
编辑
这段代码似乎没什么问题,应该将问题关闭
解决方法:
http://www.php.net/manual/en/reflectionproperty.setvalue.php
我认为您可以使用反射.
<?php
function set(array $array) {
$refl = new ReflectionClass($this);
foreach ($array as $propertyToSet => $value) {
$property = $refl->getProperty($propertyToSet);
if ($property instanceof ReflectionProperty) {
$property->setValue($this, $value);
}
}
}
$a = new A();
$a->set(
array(
'a' => 'foo',
'b' => 'bar'
)
);
var_dump($a);
输出:
object(A)[1]
public 'a' => string 'foo' (length=3)
public 'b' => string 'bar' (length=3)