in Laravel model, for instance, a class User can be initialized and properties set like below
$u = new User;
$u->name='Name';
But if I create a class in PHP like below
class X {}
$x = new X;
if I try to set other properties like below
$x->name='name';
I will receive an error telling me that the property name is not defined in class X
My question is how is it done? so that I can create a class and then be able to add properties as whenever the class is initialized even if the property does not already exist in the class
2
Answers
You can use magic getters & setters from PHP, methods
__get()
and__set()
.Also remember that dynamic properties are deprecaded on PHP 8.2.
To allow dynamic properties on PHP 8.2 use:
If you want an "unlimited" property class, even without defining a class and the contents, then just use
new stdClass()
:But I think you don’t want anything like this, you should AVOID using
stdClass
and classes that magically set stuff using__get
and__set
, because you MUST know by memory, what it has. It is considered a very BAD practice…I am not sure why you need to dynamically set stuff, but maybe a
Collection
or anarray
will solve your issue.