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

后端 未结 4 1182
抹茶落季
抹茶落季 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:14

    As of PHP7, we have Anonymous Classes which would allow you to extend a class at runtime, including setting of additional properties:

    $a = new class() extends MyObject {
        public $property1 = 1;
        public $property2 = 2;
    };
    
    echo $a->property1; // prints 1
    

    Before PHP7, there is no such thing. 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.

    If you do not need a specific class instance, but you just want a random object bag, you can also do

    $a = (object) [
        'property1' => 1,
        'property2' => 2
    ];
    

    which would then give you an instance of StdClass and which you could access as

    echo $a->property1; // prints 1
    
    0 讨论(0)
  • 2020-12-17 09:26

    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')
    ];
    
    0 讨论(0)
  • 2020-12-17 09:28

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

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题