How to call a method of anonymous object php?

I need to create anonymous object and call it’s method

$obj = new stdClass();
$obj->Greeting = function (string $d){return "Hello ".$d;};
$greetings = $obj->Greeting("world!"); 

But when I try to execute this code I get an error

Call to undefined method stdClass::Greeting()

What’s wrong?

>Solution :

You created a stdClass object, not an anonymous one:

$obj = new class () {
    public function Greeting(string $d)
        return "Hello $d";
echo $greetings = $obj->Greeting("world!");


Hello world!

What’s wrong?

Nothing, let’s just ask, what’s behind or happening here?

The stdClass is used for "empty" objects in PHP or when casting an array to an object ($obj = (object) ['hello' => 'world']).

By default it has no properties (like in $obj = new stdClass;) and also no methods. It is empty in terms of both of these.

Properties can be added dynamically to an stdClass object – but not functions as class methods have to be declared in PHP before instantiating the object.

So the function in your case is a property (PHP has two bags here: one for properties and one for functions) and not a new method dynamically added to it (class MyClass { function method() {...} }).

Let’s compare with the original example and provoke the error again:

$obj = new stdClass();
$obj->Greeting = function (string $d) {
    return "Hello $d";
$greetings = $obj->Greeting("world!"); 
PHP Fatal error:  Uncaught Error: Call to undefined method stdClass::Greeting()


echo $greetings = ($obj->Greeting)("world!");
                  #              #

works, the output:

Hello world!

because PHP is now guided to "call" the ($obj->Greeting) property indirectly, so not looking for the stdClass::Greeting method first.

Normally you don’t want that indirection, therefore the suggestion to use the anonymous class instead.

Leave a Reply