399

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?

3
  • 4
    Check this answer : stackoverflow.com/a/6384474/1606729 Commented Jan 18, 2013 at 9:14
  • 1
    $obj = (object)[]; $obj->someProp = "hey boy"; Commented May 13, 2016 at 10:26
  • PHP's nested, associative arrays might be a good replacement for nested JS objects depending on what you're trying to do. Commented May 10, 2019 at 15:22

1 Answer 1

840

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'];
Sign up to request clarification or add additional context in comments.

5 Comments

+1 for the PHP 5.4 method, this makes code shorter, more readable, especially when you have several items to add to the object.
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.
Another way, using single json_decode, is passing a JSON-string: $object = json_decode('{"property": {"foo": "bar"}, "hello": "world"}');
@DavidRouten That was super super helpful. Thank you.
@DavidRouten Seems like PHP7.4 (or even earlier?) now also creates nested objects when you use (object) $array.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.