Creating anonymous objects in php

Viewed 96434

As we know, creating anonymous objects in JavaScript is easy, like the code below:

var object = { 
    p : "value", 
    p1 : [ "john", "johnny" ]
};

alert(object.p1[1]);

Output:

an alert is raised with value "johnny"

Can this same technique be applied in PHP? Can we create anonymous objects in PHP?

12 Answers

Support for anonymous classes has been available since PHP 7.0, and is the closest analogue to the JavaScript example provided in the question.

<?php
$object = new class {
    var $p = "value";
    var $p1 = ["john", "johnny"];
};

echo $object->p1[1];

The visibility declaration on properties cannot be omitted (I just used var because it's shorter than public.)

Like JavaScript, you can also define methods for the class:

<?php
$object = new class {
    var $p = "value";
    var $p1 = ["john", "johnny"];
    function foo() {return $this->p;}
};

echo $object->foo();

For one who wants a recursive object:

$o = (object) array(
    'foo' => (object) array(
        'sub' => '...'
    )
);

echo $o->foo->sub;

From the PHP documentation, few more examples:

<?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) {}

?>

$obj1 and $obj3 are the same type, but $obj1 !== $obj3. Also, all three will json_encode() to a simple JS object {}:

<?php

echo json_encode([
    new \stdClass,
    new class{},
    (object)[],
]);

?>

Outputs:

[{},{},{}]

https://www.php.net/manual/en/language.types.object.php

Anoynmus object wiki


$object=new class (){


};

Related