How to set attributes for stdClass object at the time object creation

后端 未结 3 872
一个人的身影
一个人的身影 2021-02-03 18:40

I want to set attribute for a stdClass object in a single statement. I don\'t have any idea about it. I know the following things

$obj = new stdClass;
$         


        
3条回答
  •  醉话见心
    2021-02-03 18:46

    $obj = (object) array(
        'attr'=>'loremipsum'
    );
    

    Actually, that's as direct as it's going to get. Even a custom constructor won't be able to do this in a single expression.

    The (object) cast might actually be a simple translation from an array, because internally the properties are stored in a hash as well.

    You could create a base class like this:

    abstract class MyObject
    {
        public function __construct(array $attributes = array())
        {
            foreach ($attributes as $name => $value) {
                $this->{$name} = $value;
            }
        }
    }
    
    class MyWhatever extends MyObject
    {
    }
    
    $x = new MyWhatever(array(
        'attr' => 'loremipsum',
    ));
    

    Doing so will lock up your constructor though, requiring each class to call its parent constructor when overridden.

提交回复
热议问题