Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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()

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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!");

output:

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()

However:

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading