如何从对象方法内的给定参数创建属性?
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;
我是否可以将财产设为公共/受保护/私有?我知道在这种情况下它应该是公开的,但我可能想添加一些magik方法来获取受保护的属性和东西:)
I think I found a solution:
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];
}
你认为这是个好主意吗?
有两种方法可以做到这一点。
一,您可以直接从类外部动态创建属性:
class Foo{
}
$foo = new Foo();
$foo->hello = 'Something';
或者,如果您希望通过您的createProperty
method:
class Foo{
public function createProperty($name, $value){
$this->{$name} = $value;
}
}
$foo = new Foo();
$foo->createProperty('hello', 'something');
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)