389

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?

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
Wolfgang Adamec
  • 8,374
  • 12
  • 50
  • 74

1 Answers1

826

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'];
Artem L
  • 10,123
  • 1
  • 20
  • 15
  • 42
    +1 for the PHP 5.4 method, this makes code shorter, more readable, especially when you have several items to add to the object. – mark Feb 17 '16 at 10:11
  • 32
    If you are looking at turning a nested array into an object, I'd recommend using `json_decode(json_encode($array))` which will turn the entire array into a nested stdClass object. If you use `(object) $array` it will only convert the first layer into an object, everything nested inside that will remain an array. – David Routen Mar 02 '18 at 20:29
  • 2
    Another way, using single json_decode, is passing a JSON-string: $object = json_decode('{"property": {"foo": "bar"}, "hello": "world"}'); – n.r. Mar 14 '18 at 21:58
  • 1
    @DavidRouten That was super super helpful. Thank you. – Ryan May 26 '18 at 15:35
  • 1
    @DavidRouten Seems like PHP7.4 (or even earlier?) now also creates nested objects when you use (object) $array. – n.r. Sep 22 '20 at 08:14