php create object without class

Php

Php Problem Overview


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?

Php Solutions


Solution 1 - Php

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'];

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionWolfgang AdamecView Question on Stackoverflow
Solution 1 - PhpArtem LView Answer on Stackoverflow