I know that in C# you can nowadays do:
var a = new MyObject
{
Property1 = 1,
Property2 = 2
};
Is there something like that in PHP too? Or should I just do it through a constructor or through multiple statements;
$a = new MyObject(1, 2);
$a = new MyObject();
$a->property1 = 1;
$a->property2 = 2;
If it is possible but everyone thinks it’s a terrible idea, I would also like to know.
PS: the object is nothing more than a bunch of properties.
As of PHP7, we have Anonymous Classes which would allow you to extend a class at runtime, including setting of additional properties:
Before PHP7, there is no such thing. If the idea is to instantiate the object with arbitrary properties, you can do
Add variations as you see fit. For instance, add checks to
property_existsto only allow setting of defined members. I find throwing random properties at objects a design flaw.If you do not need a specific class instance, but you just want a random object bag, you can also do
which would then give you an instance of StdClass and which you could access as