elepil
asked on
PHP, is it possible to store a function in stdClass?
Look at this code snippet:
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:
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.
$s = new stdClass();
$s->sayHello = function() {
echo "Hello World!";
}; // This definition would not get an error
$s->sayHello(); // This line would get an error
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()
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
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
As of PHP 5.3, you can use anonymous functions like that, yes.
http://php.net/manual/en/functions.anonymous.php
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.
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%.
ASKER