如何dynamic创build新的属性

我怎样才能创build一个对象的方法内给定的参数的属性?

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方法来获得保护属性和东西:)


我想我find了一个解决scheme:

  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]; } 

你认为这是一个好主意吗?

有两种方法来做到这一点。

一,你可以直接从课外dynamic创build属性:

 class Foo{ } $foo = new Foo(); $foo->hello = 'Something'; 

或者,如果您希望通过createProperty方法创build属性:

 class Foo{ public function createProperty($name, $value){ $this->{$name} = $value; } } $foo = new Foo(); $foo->createProperty('hello', 'something'); 

属性重载很慢。 如果可以的话,尽量避免它。 另外重要的是实施其他两个神奇的方法:

__isset(); __unset();

如果以后不想在使用这些对象“属性”时发现一些常见的错误,

这里有些例子:

http://www.php.net/manual/en/language.oop5.overloading.php#language.oop5.overloading.members

亚历克斯评论后编辑:

您可以检查两种解决scheme之间的时间差异(更改$ REPEAT_PLEASE)

 <?php $REPEAT_PLEASE=500000; class a {} $time = time(); $a = new a(); for($i=0;$i<$REPEAT_PLEASE;$i++) { $a->data = 'hi'; $a->data = 'bye'.$a->data; } echo '"NORMAL" TIME: '.(time()-$time)."\n"; class b { function __set($name,$value) { $this->d[$name] = $value; } function __get($name) { return $this->d[$name]; } } $time=time(); $a = new b(); for($i=0;$i<$REPEAT_PLEASE;$i++) { $a->data = 'hi'; //echo $a->data; $a->data = 'bye'.$a->data; } echo "TIME OVERLOADING: ".(time()-$time)."\n"; 

使用语法:$ object – > {$ property}其中$ property是一个stringvariables,$ object可以是this,如果它在类或任何实例对象

现场示例: http : //sandbox.onlinephpfunctions.com/code/108f0ca2bef5cf4af8225d6a6ff11dfd0741757f

  class Test{ public function createProperty($propertyName, $propertyValue){ $this->{$propertyName} = $propertyValue; } } $test = new Test(); $test->createProperty('property1', '50'); echo $test->property1; 

结果:50

以下示例适用于不想声明整个类的人。

 $test = (object) []; $prop = 'hello'; $test->{$prop} = 'Hiiiiiiiiiiiiiiii'; echo $test->hello; // prints Hiiiiiiiiiiiiiiii