Is it possible to add data members dynamically in

2019-05-10 21:33发布

I'm wondering if its possible to add new class data members at run-time in PHP?

标签: php oop
2条回答
The star\"
2楼-- · 2019-05-10 21:54

Yes.

$prop = 'newname';
$obj->$prop = 42;

will do the same thing as:

$obj->newname = 42;

Either one will add "newname" as a property in $obj if it does not yet exist.

查看更多
beautiful°
3楼-- · 2019-05-10 22:06

It is. You can add public members are run time with no additional code, and can affect protected/private members using the magical overloading methods __get() / __set(). See here for more details.

查看更多
登录 后发表回答