将方法分配给变量/属性

时间:2016-02-02 18:52:24

标签: php functional-programming anonymous-function php-5.5

以下是非常简化的示例。我想知道在PHP中是否可行,如果是这样,那么正确的语法是什么。

class A{
   private $func = null;

   private default_func(){
       return $this;
   }

   public function __construct(callable $user_func=null){
      if($user_func){
          $this->func = $user_func;
      else{
          $this->func = $this->default_func; ********* NOT WORKING ******
      }

    }

    public function run(){
      $this->func();*************** NOT WORKING IF USER DOES NOT GIVE def func
  }
}

//NOT WORKING
$C = new A;
$C->run();

//WORKS
$D = new A(function(){echo 1;});
$D->run();

我在这里尝试让开发人员能够将一个函数发送到类中,以便运行时覆盖默认行为。
我完全知道我可以简单地在else中调用默认函数,但如前所述,这是一个简单的例子。实际上有许多“默认”功能。

3 个答案:

答案 0 :(得分:2)

您可以使用call_user_func()来调用所需的功能。这可以让您管理要呼叫的那个。

  public function __construct(callable $user_func=null){
      if($user_func){
          $this->func = $user_func;
      else{
          $this->func = [$this, 'default_func'];
      }

      call_user_func($this->func);
  }

答案 1 :(得分:2)

你可以这样做:

        class A{
           private $func = function(){
               return $this;
           };

           public function __construct(callable $user_func=null){
              if($user_func){
                  $this->func = $user_func;
              }

              $this->func();
          }
        }

但更好:

{{1}}

答案 2 :(得分:1)

将默认函数包含在闭包中,如此

class A{
   private $func = null;

   public function __construct(callable $user_func=null){
      if($user_func){
          $this->func = $user_func;
      else{
          $this->func = function(){
                    return $this;
          } 
      }

      $this->func();
  }
}