Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to add data members dynamically in PHP?

Tags:

oop

php

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

like image 738
fuentesjr Avatar asked Dec 10 '22 23:12

fuentesjr


2 Answers

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.

like image 144
Andru Luvisi Avatar answered Dec 13 '22 13:12

Andru Luvisi


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.

like image 36
Eran Galperin Avatar answered Dec 13 '22 15:12

Eran Galperin