类中的匿名函数

时间:2012-09-26 13:22:45

标签: php

有没有更好的方法在类中调用匿名函数?这是一个简单的例子,清楚我的意思。

class foo
{
     private $call_back_1 = null;
     private $call_back_2 = null;

     function __construct($func1, $func2)
     {
          $this->call_back_1 = func1;
          $this->call_back_2 = func2;
     }


     function provokeCallBacks()
     {
          //this does not work, and gives an error  
          $this->call_back_1();


          //I would like to avoid this
          $method = $this->call_back_2;
          $method(); 
     }
}

$call1 = function(){ echo "inside call 1"};
$call2 = function(){ echo "inside call 2"};

$test = new foo(call1, call2);

$test->provokeCallBacks();

*更新1:请忽略任何语法错误,因为我已经动态地为演示文件写了这个。 *

在foo:provokeCallBacks中,我试图调用匿名函数,如果第一种方法不起作用并给出错误。第二个工作,但有点愚蠢,我必须使用一个名为“$ method”的临时变量来进行调用。

我想知道是否有更好的方法来调用匿名函数。

5 个答案:

答案 0 :(得分:4)

call_user_func($this->call_back_1);

答案 1 :(得分:2)

不,无法通过$this调用匿名函数。

另一个选择是;

call_user_func($this->call_back_1);

答案 2 :(得分:2)

PHP松散输入,它不能像{$this -> callback}()那样;你必须将它存储在临时变量中或使用call_user_func()

编辑 - 考虑这样的事情:

class Lambdas
{

    protected $double;
    protected $triple;  

    public function __construct($double, $triple)
    {

        $this -> double = $double;
        $this -> triple = $triple;      

    }

    public function __call($name, $arguments)
    {

        if( is_callable($this -> {$name}) ){

            return call_user_func_array($this -> {$name}, $arguments);

        }

    }

}

$lambdas = new Lambdas(
    function($a){ return $a * 2;},
    function($a){ return $a * 3;}
);

echo $lambdas -> double(2); // prints 4
echo $lambdas -> triple(2); // prints 6

答案 3 :(得分:1)

肮脏且危险,但你可能成功使用eval ..

class foo
{
  private $call_back_1 = null;
  private $call_back_2 = null;

  function __construct($func1, $func2)
  {
      $this->call_back_1 = func1;
      $this->call_back_2 = func2;
  }


  function provokeCallBacks()
  {
      eval($this->call_back_1);
      eval($this->call_back_2);
  }
}

call1 = 'echo "inside call 1"';
call2 = 'echo "inside call 2"';

$test = foo(call1, call2);

$test->provokeCallBacks();

答案 4 :(得分:1)

我知道您的问题已得到解答,但您可以尝试更改您的方法..

class Foo {
    private $calls = array();
    function __set($key, $value) {
        $this->calls[$key] = $value;
    }
    function __call($name, $arg) {
        if (array_key_exists($name, $this->calls)) {
            $this->calls[$name]();
        }
    }

    function __all() {
        foreach ( $this->calls as $call ) {
            $call();
        }
    }
}

$test = new Foo();

$test->A = function () {
    echo "inside call 1";
};

$test->B = function () {
    echo "inside call 2";
};

$test->A(); // inside call 1
$test->B(); // inside call 2
$test->__all(); // inside call 1 & inside call 2