0

What other ways can you build a stdClass object similar to an associative array without using a loop, other than

$obj = (object)[ 'item1' => 1 , 'item2'=> 2 ];

Similar to how you can create an object in Javascript

var obj = { item1 : 1 , item : 2 }

Thank you in advance.

2
  • Check out the PHP objects page... Commented Oct 18, 2017 at 19:02
  • $obj = new stdClass(); $obj->item1 = 1; $obj->item2 = 2; Commented Oct 18, 2017 at 19:03

1 Answer 1

1

According to Anthony on PHP Manual:

In PHP 7 there are a few ways to create an empty object:

<?php
$obj1 = new \stdClass; // Instantiate stdClass object
$obj2 = new class{}; // Instantiate anonymous class
$obj3 = (object)[]; // Cast empty array to object

var_dump($obj1); // object(stdClass)#1 (0) {}
var_dump($obj2); // object(class@anonymous)#2 (0) {}
var_dump($obj3); // object(stdClass)#3 (0) {}
?>

For more on what he had to say visit the PHP Manual documentation with his answer.

To expand on his answer, the first one would look like this:

First example

$obj1 = new \stdClass;
$obj1->first = 1;

print_r($obj1);

// output
// stdClass Object
// (
//     [first] => 1
// )

Second example

$obj2 = new class{ };
$obj2->second = 2;

print_r($obj2);

// output
// class@anonymous Object
// (
//     [second] => 2
// )

Third example

$obj3 = (object)[];
$obj3->third = 3;

print_r($obj3);

// output
// stdClass Object
// (
//     [third] => 3
// )

You could do something along those lines; it's as easy as that

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.