PHP动态设置对象属性 [英] PHP set object properties dynamically
本文介绍了PHP动态设置对象属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个函数,该函数应该读取数组并动态设置对象属性.
I have a function, that should read array and dynamically set object properties.
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);
好吧,显然这是行不通的,有没有办法做到这一点?
Well, obviously it doesn't work, is there a way to do this?
编辑
这段代码似乎没什么问题,这个问题应该关闭
It seems that nothing is wrong with this code, the question should be closed
推荐答案
http://www.php.net/manual/zh-CN/reflectionproperty.setvalue.php
我认为您可以使用Reflection
.
<?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)
这篇关于PHP动态设置对象属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文