Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php create object without class [duplicate]

Tags:

php

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?

like image 937
Wolfgang Adamec Avatar asked Jan 18 '13 09:01

Wolfgang Adamec


People also ask

How do you create a new 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.

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.

What is cloning object in PHP?

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.

What is object in PHP with example?

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.


1 Answers

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']; 
like image 141
Artem L Avatar answered Oct 16 '22 02:10

Artem L