4

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

2 Answers 2

12

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.

Sign up to request clarification or add additional context in comments.

Comments

2

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.