如何从对象的方法中的给定参数创建一个属性?
class Foo{
public function createProperty($var_name, $val){
// here how can I create a property named "$var_name"
// that takes $val as value?
}
}
我想要能够访问的属性,如:
$object = new Foo();
$object->createProperty('hello', 'Hiiiiiiiiiiiiiiii');
echo $object->hello;
还有可能,我可以使属性public / protected / private?我知道在这种情况下,它应该是公共的,但我可能想添加一些magik方法来获得受保护的属性和东西:)
我想我找到了一个解决方案:
protected $user_properties = array();
public function createProperty($var_name, $val){
$this->user_properties[$var_name] = $val;
}
public function __get($name){
if(isset($this->user_properties[$name])
return $this->user_properties[$name];
}
你认为这是个好主意吗?