In PHP, you can initialize arrays with values quickly using the following notation:
$array = array("name" => "member 1", array("name" => "member 1.1") ) ....
is there any way to do this for STDClass objects? I don't know any shorter way than the dreary
$object = new STDClass(); $object->member1 = "hello, I'm 1"; $object->member1->member1 = "hello, I'm 1.1"; $object->member2 = "hello, I'm 2";
PHP allocates memory dynamically and what's more, it doesn't care what sort of object you store in your array. If you want to declare your array before you use it something along these lines would work: var $myArray = array(); Then you can store any object you like in your variable $myArray.
An object is an instance of a class. It is simply a specimen of a class and has memory allocated. Array is the data structure that stores one or more similar type of values in a single name but associative array is different from a simple PHP array.
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.
One way to initialize the array of objects is by using the constructors. When you create actual objects, you can assign initial values to each of the objects by passing values to the constructor. You can also have a separate member method in a class that will assign data to the objects.
You can use type casting:
$object = (object) array("name" => "member 1", array("name" => "member 1.1") );
I also up-voted Gumbo as the preferred solution but what he suggested is not exactly what was asked, which may lead to some confusion as to why member1o
looks more like a member1a
.
To ensure this is clear now, the two ways (now 3 ways since 5.4) to produce the same stdClass
in php.
As per the question's long or manual approach:
$object = new stdClass; $object->member1 = "hello, I'm 1"; $object->member1o = new stdClass; $object->member1o->member1 = "hello, I'm 1o.1"; $object->member2 = "hello, I'm 2";
The shorter or single line version (expanded here for clarity) to cast an object from an array, ala Gumbo's suggestion.
$object = (object)array( 'member1' => "hello, I'm 1", 'member1o' => (object)array( 'member1' => "hello, I'm 1o.1", ), 'member2' => "hello, I'm 2", );
PHP 5.4+ Shortened array declaration style
$object = (object)[ 'member1' => "hello, I'm 1", 'member1o' => (object)['member1' => "hello, I'm 1o.1"], 'member2' => "hello, I'm 2", ];
Will both produce exactly the same result:
stdClass Object ( [member1] => hello, I'm 1 [member1o] => stdClass Object ( [member1] => hello, I'm 1o.1 ) [member2] => hello, I'm 2 )
nJoy!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With