Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

php

stdclass

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; $obj->attr = 'loremipsum'; 

It takes two statements.

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

It takes single statement but it is not direct method.

$obj = new stdClass(array('attr'=>'loremipsum')); 

It is not working.

like image 568
Mohammed H Avatar asked Dec 07 '12 10:12

Mohammed H


People also ask

What is stdClass object in PHP?

The stdClass is the empty class in PHP which is used to cast other types to object. It is similar to Java or Python object. The stdClass is not the base class of the objects. If an object is converted to object, it is not modified.

How do I declare an object in PHP?

To create an Object in PHP, use the new operator to instantiate a class. If a value of any other type is converted to an object, a new instance of the stdClass built-in class is created.

How do I print a stdClass?

If you just want to print you can use var_dump() or print_r() . var_dump($obj); print_r($obj); If you want an array of all properties and their values use get_object_vars() .


2 Answers

$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.

like image 167
Ja͢ck Avatar answered Sep 22 '22 11:09

Ja͢ck


Though Ja͢ck gives a good answer, it is important to stress that the PHP interpreter itself has a method for describing how to properly represent an object or variable:

php > $someObject = new stdClass(); php > $someObject->name = 'Ethan'; php > var_export($someObject); stdClass::__set_state(array(    'name' => 'Ethan', )) 

Interestingly, using stdClass::__set_state fails to create a stdClass object, thus displaying it as such is likely a bug in var_export(). However, it does illustrate that there is no straightforward method to create the stdClass object with attributes set at the time of object creation.

like image 32
dotancohen Avatar answered Sep 19 '22 11:09

dotancohen