Note: I have condensed this article into my person wiki: http://wiki.chacha102.com/Lambda - Enjoy
I am having some troubles with Lambda style functions in PHP.
First, This Works:
$foo = function(){ echo "bar"; };
$foo();
Second, This Works:
class Bar{
public function foo(){
echo "Bar";
}
Third, This works:
$foo = new stdClass;
$foo->bar = function(){ echo "bar"; };
$test = $foo->bar;
$test();
But, this does not work:
$foo = new stdClass;
$foo->bar = function(){ echo "bar"; };
$foo->bar();
And, this does not work
class Bar{
public function foo(){
echo "Bar";
}
$foo = new Bar;
$foo->foo = function(){ echo "foo"; };
$foo->foo(); // echo's bar instead of Foo.
My Question is Why?, and how can I assure that both this:
$foo->bar = function(){ echo "test"; };
$foo->bar();
and this
$foo = new Bar;
$foo->bar();
are called properly? Extra Points if you can point to documentation stating why this problem occurs.
Introduction. Anonymous function is a function without any user defined name. Such a function is also called closure or lambda function. Sometimes, you may want a function for one time use. Closure is an anonymous function which closes over the environment in which it is defined.
PHP User Defined Functions Besides the built-in PHP functions, it is possible to create your own functions. A function is a block of statements that can be used repeatedly in a program. A function will not execute automatically when a page loads. A function will be executed by a call to the function.
The declaration of a user-defined function starts with the word function, followed by the name of the function you want to create followed by parentheses i.e. () and finally place your function's code between curly brackets {}.
Advantages of PHP FunctionReusability of Code: Unlike other programming languages, PHP Functions are specified only once and can be called multiple times. Less Code: It saves a lot of code because the logic doesn't have to be written several times. You can write the logic only once and reuse it by using functions.
This is an interesting question. This works:
$a = new stdClass;
$a->foo = function() { echo "bar"; };
$b = $a->foo;
$b(); // echos bars
but as you say this doesn't:
$a = new stdClass;
$a->foo = function() { echo "bar"; };
$a->foo();
If you want an object to which you can dynamically call members, try:
class A {
public function __call($func, $args) {
$f = $this->$func;
if (is_callable($f)) {
return call_user_func_array($f, $args);
}
}
}
$a = new A;
$a->foo = function() { echo "bar\n"; };
$a->foo2 = function($args) { print_r($args); };
$a->foo();
$a->foo2(array(1 => 2, 3 => 4));
But you can't replace callable methods this way because __call()
is only called for methods that either don't exist or aren't accessible (eg they're private).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With