In JavaScript, you can easiliy create an object without a class by:
myObj = {}; myObj.abc = "aaaa";
For PHP I've found this one, but it is nearly 4 years old: http://www.subclosure.com/php-creating-anonymous-objects-on-the-fly.html
$obj = (object) array('foo' => 'bar', 'property' => 'value');
Now with PHP 5.4 in 2013, is there an alternative to this?
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.
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.
The clone keyword is used to create a copy of an object. If any of the properties was a reference to another variable or object, then only the reference is copied. Objects are always passed by reference, so if the original object has another object in its properties, the copy will point to the same object.
In PHP, Object is a compound data type (along with arrays). Values of more than one types can be stored together in a single variable. Object is an instance of either a built-in or user defined class. In addition to properties, class defines functionality associated with data.
you can always use new stdClass()
. Example code:
$object = new stdClass(); $object->property = 'Here we go'; var_dump($object); /* outputs: object(stdClass)#2 (1) { ["property"]=> string(10) "Here we go" } */
Also as of PHP 5.4 you can get same output with:
$object = (object) ['property' => 'Here we go'];
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