【发布时间】:2012-02-01 04:41:46
【问题描述】:
如何从对象方法中的给定参数创建属性?
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 吗?我知道在这种情况下它应该是公开的,但我可能想添加一些魔法方法来获取受保护的属性和东西:)
我想我找到了解决方案:
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];
}
你认为这是个好主意吗?
【问题讨论】:
标签: php object properties