【问题标题】:PHP Closure returns an objectPHP 闭包返回一个对象
【发布时间】:2015-01-15 23:55:16
【问题描述】:

闭包允许我使用例如:

$app->register('test', function() { return 'test closure'; });
echo $app->test();

问题是,当闭包返回一个对象时它不起作用。如:

$app->register('router', function() { return new Router(); });
$app->router->map($url, $path);

我得到:Fatal error: Call to undefined method Closure::map() in index.php on line 22

/** app.php **/
class App {
    public function __construct(){
        $this->request = new Request();
        $this->response = new Response();
    }
    public function register($key, $instance){
        $this->$key = $instance;
    }
    public function __set($key, $val){
        $this->$key = $val;
    }
    public function __get($key){
        if($this->$key instanceof Closure){
            return $this->$key();
        }else return $this->$key;
    }
    public function __call($name, $args){
        $closure = $this->$name;
        call_user_func_array( $closure, $args ); // *
    }
}

/** router.php **/
class Router {
    public function map($url, $action){

    }  
}

插件详情:

有效:

$app->register('router', new Router());
$app->router->map($url, $action);

但是在闭包中返回对象的目的是根据需要提供最后一分钟的配置...我尝试对此进行研究,但是大多数主题只是描述了如何调用闭包,我已经理解了。这就是为什么app类中有一个__call方法...

编辑:

$app->router()->map($url, $action);
Fatal error: Call to a member function map() on null in

【问题讨论】:

    标签: php closures


    【解决方案1】:

    关键是闭包返回一个闭包对象,这就是它与“Does work”版本不同的原因。

    当你打电话时

    $app->router()
    

    __call,而不是__get,所以你什么也得不到,因为你的类中没有定义可调用的路由器。我认为没有直接的语法可以做你想做的事,你必须通过一个临时变量,比如:

    $temp = $app->router;
    $temp()->map($url, $action);
    

    【讨论】:

    • 实际上有可能...在__call 方法中,我不得不返回call_user_func_array 调用。现在,我可以根据需要使用:$app->router()->map('url', 'action');...
    猜你喜欢
    • 2013-07-07
    • 2010-10-22
    • 1970-01-01
    • 2014-08-10
    • 2012-09-12
    • 2018-12-29
    • 2014-10-15
    • 1970-01-01
    • 2020-08-12
    相关资源
    最近更新 更多