Search code examples
phpobjectstdclass

Build PHP stdClass object simular to an Associative Array


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.


Solution

  • 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