Is there a special object initializer construct in PHP like there is now in C#?

Viewed 4253

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.

4 Answers

I went from c# to PHP too, so I got this working in PHP:

$this->candycane = new CandyCane(['Flavor' => 'Peppermint', 'Size' => 'Large']);

My objects have a base class that checks to see if there's one argument and if it's an array. If so it calls this:

public function LoadFromRow($row){
    foreach ($row as $columnname=>$columnvalue)
        $this->__set($columnname, $columnvalue);
}

It also works for loading an object from a database row. Hence the name.

Another way, which is not the proper way but for some cases okay:

class Dog
{
    private $name;
    private $age;

    public function setAge($age) {
        $this->age = $age;
        return $this;
    }

    public function getAge() {
        return $this->age;
    }

    public function setName($name) {
        $this->name = $name;
        return $this;
    }

    public function getName() {
        return $this->name;
    }
}

$dogs = [
    1 => (new Dog())->setAge(2)->setName('Max'),
    2 => (new Dog())->setAge(7)->setName('Woofer')
];
Related