【问题标题】:PHP callback - how to execute it in a class?PHP 回调 - 如何在类中执行它?
【发布时间】:2016-01-01 00:36:11
【问题描述】:

我试图了解在现代框架中路由请求时 PHP 闭包/函数回调的流行用法。例如,Slim 允许您执行以下操作:

$app->get('/hello/:name', function ($name) {
    echo "Hello, $name";
});
$app->run();

我的实验:

class Foo
{
    private $string;
    private $callback;

    public function get($string, $callback)
    {
        $this->string = $string;
        $this->callback = $callback;
    }

    public function run()
    {
        return $this->get($this->string, $this->callback);
    }
}

$Foo = new Foo;
$Foo->get('/world', function($name) {
    return "Hello " . $name;
});

$Foo->run();

如何在类中执行回调,使其返回Hello World

【问题讨论】:

    标签: php lambda closures anonymous-function php-5.6


    【解决方案1】:

    在设计框架时,它会稍微复杂一些,以便获得更好的灵活性。
    但在这个简单的案例中,您只需使用call_user_func_array()call_user_func()。我建议使用call_user_func_array(),因为它在传递许多参数时更容易:

    class Foo
    {
        private $string;
        private $callback;
    
        public function get($string, callable $callback)
        {
            $this->string = $string;
            $this->callback = $callback;
        }
    
        public function run()
        {
             return call_user_func_array($this->callback, [$this->string]);
            # OR 
            # return call_user_func($this->callback, $this->string);
            # OR
            #$fn = $this->callback; return $fn($this->string);
    
        }
    }
    
    $Foo = new Foo;
    $Foo->get('/world', function($name) {
        return "Hello " . $name;
    });
    
    print $Foo->run();
    

    【讨论】:

      【解决方案2】:

      根据您的示例代码,应该是这样的:

          public function get($string, $callback)
          {
              //assign input parameter to object's propety
              $this->string = $string;
              $this->callback = $callback;
      
          }
      
          public function run()
          {
              /* if you want to avoid using this variable
                 use call_user_func */
              $callback = $this->callback;
      
              // run the callback
              return $callback($this->string);
          }
      }
      
      $Foo = new Foo;
      $Foo->get('world', function($name) {
          return "Hello " . $name;
      });
      
      $return = $Foo->run();
      var_dump($return); //this will return 'Hello world'
      

      【讨论】:

      • 抱歉,我在发帖时没有看到@elipsmartins 的回答——我写的时候还没有。我们的答案其实是一样的。我还是 Stackoverflow 的新手。
      • 不用担心。它也有帮助! ;)
      猜你喜欢
      • 1970-01-01
      • 2023-03-15
      • 1970-01-01
      • 2013-08-19
      • 2010-11-04
      • 1970-01-01
      • 2015-05-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多