Link to home
Start Free TrialLog in
Avatar of elepil
elepil

asked on

PHP, is it possible to store a function in stdClass?

Look at this code snippet:

$s = new stdClass();
    $s->sayHello = function() {
        echo "Hello World!";
    }; // This definition would not get an error
    
    $s->sayHello(); // This line would get an error

Open in new window


Somehow, I am able to store a function in stdClass without any errors. But when I try to invoke the function, I get this error message:

PHP Fatal error:  Call to undefined method stdClass::sayHello()

Open in new window


I wish it would give me an error when I defined the function, then I'd know I can't do such a thing. But to let me store a function in stdClass and then give me an error gives me the impression that I'm just not doing something right. So what am I doing wrong?

Thanks.
ASKER CERTIFIED SOLUTION
Avatar of Ray Paseur
Ray Paseur
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of elepil
elepil

ASKER

Thanks, Ray.
As of PHP 5.3, you can use anonymous functions like that, yes.

http://php.net/manual/en/functions.anonymous.php

$greet = function($name)
{
    printf("Hello %s\r\n", $name);
};

$greet('World');
$greet('PHP');

Changelog

Version      Description
5.4.0      $this can be used in anonymous functions.
5.3.0      Anonymous functions become available.
Anonymous functions are one thing and they seem fine in procedural code; getting them to work sensibly with StdClass is another.  Also, PHP built-in classes have some "interesting" side effects when you try to use the object they create.
http://php.net/manual/en/function.unserialize.php#112823

Closures have some of the characteristics of programming and some of the characteristics of data.  Is a closure that was added to an object a method or a property of the object?  The behavior and documentation do not make this difference clear (at least not to me).  So I think that the right practice might be to avoid any ambiguity and risk.  It's so easy to create our own classes, and their behavior is predictable and sensible.
Agreed 100%.