Lambda Functions in PHP aren't Logical Lambda Functions in PHP aren't Logical php php

Lambda Functions in PHP aren't Logical


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


Functions and methods are treated differently in PHP. You can use runkit_method_add() to add a method to a class, but I know of no way to add a method to an instance.


Interesting question although I see no reason why this should work:

class Bar{    public function foo(){       echo "Bar";    }$foo = new Bar;$foo->foo = function(){ echo "foo"; };$foo->foo(); // echo's bar instead of Foo.

I had a similar problem with __invoke(), and I've also not been able to solve it:

class base {    function __construct() {        $this->sub = new sub();    }    function __call($m, $a) {    }}class sub {    function __invoke($a) {    }}$b = new base();$b->sub('test'); // should trigger base::__call('sub', 'test') or sub::__invoke('test')?

Solution? Never use __invoke()! :P