Initialize Objects like arrays in PHP?

后端 未结 8 1438
情话喂你
情话喂你 2021-01-01 09:04

In PHP, you can initialize arrays with values quickly using the following notation:

$array = array(\"name\" => \"member 1\", array(\"name\" => \"member         


        
相关标签:
8条回答
  • 2021-01-01 09:59

    from this answer to a similar question:

    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
    

    It's not as succinct as the initializer for array. Not sure if I'd use it. But it is another option you can consider.

    0 讨论(0)
  • 2021-01-01 10:02

    You can use :

    $object = (object)[]; // shorter version of (object)array();
    
    $object->foo = 'bar';
    
    0 讨论(0)
提交回复
热议问题