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

后端 未结 4 1207
抹茶落季
抹茶落季 2020-12-17 08:33

I know that in C# you can nowadays do:

var a = new MyObject
{
    Property1 = 1,
    Property2 = 2
};

Is there something like that in PHP t

4条回答
  •  孤街浪徒
    2020-12-17 09:37

    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.

提交回复
热议问题