闭包允许我使用例如:
$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);
但是在闭包中返回对象的目的是根据需要提供最后一分钟的配置......我尝试研究这个,但是大多数主题只是描述如何调用闭包,我已经理解了。这就是为什么应用程序类中有一个__call方法的原因......
编辑:
$app->router()->map($url, $action);
Fatal error: Call to a member function map() on null in
关键是闭包返回一个 Closure 对象,这就是为什么它与"确实有效"版本不同。
同样当你打电话时
$app->router()
__call
启动,而不是__get
,所以你什么也得不到,因为你的类中没有定义可调用的路由器。我认为没有直接的语法可以做你想做的事情,你必须通过一个临时变量,例如:
$temp = $app->router;
$temp()->map($url, $action);