views:

28

answers:

2

I know that in C# you can nowadays do:

MyObject 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.

+3  A: 

Something like in C# does not exist in PHP. Use your alternate approaches.

if the idea is to instantiate the object with arbitrary properties, you can do

public function __construct(array $properties)
{
    foreach($properties as $property => $value) {
        $this->$property = $value
    }
}
$foo = new Foo(array('prop1' => 1, 'prop2' => 2));

Add variations as you see fit. For instance, add checks to property_exists to only allow setting of defined members. I find throwing random properties at objects a design flaw.

Gordon
Thanks. The idea was not to instiate aribitrary properties. Thanks anyway for the idea. I'll use my first alternative: A constructor.
Matthijs Wessels
+1  A: 

I suggest you use a constructor and set the variables you wish when initialising the object.

Thariama
Thanks for your answer, I will do that.
Matthijs Wessels