在php中,函数返回另一个函数


A function returns another function in php

我不知道这个问题(我问的方式)是否正确。我愿意接受你的建议。我想知道下面的代码是如何工作的。如果你需要任何细节,我可以尽可能多地提供。

public function processAPI() {
    if (method_exists($this, $this->endpoint)) {
        return $this->_response($this->{$this->endpoint}($this->args));
    }
    return $this->_response("No Endpoint: $this->endpoint", 404);
}
private function _response($data, $status = 200) {
    header("HTTP/1.1 " . $status . " " . $this->_requestStatus($status));
    return json_encode($data);
}
private function _requestStatus($code) {
    $status = array(  
        200 => 'OK',
        404 => 'Not Found',   
        405 => 'Method Not Allowed',
        500 => 'Internal Server Error',
    ); 
    return ($status[$code])?$status[$code]:$status[500]; 
}
/**
 * Example of an Endpoint
 */
 protected function myMethod() {
    if ($this->method == 'GET') {
        return "Your name is " . $this->User->name;
    } else {
        return "Only accepts GET requests";
    }
 }

这里是$this->endpoint is 'myMethod' (a method I want to execute)

传递我想在url中执行的方法。该函数捕获请求进程,然后调用确切的方法。我想知道它是怎么运作的。尤其是这一行

return $this->_response($this->{$this->endpoint}($this->args));

PHP支持变量函数和可变变量

当它到达processApi

中的语句时
return $this->_response($this->{$this->endpoint}($this->args));

PHP将解析你的端点变量,我们将把它替换为myMethod,在你的例子中:

return $this->_response($this->myMethod($this->args));

正如你所看到的,我们现在调用了一个存在于你的类中的方法。如果您将端点设置为不存在的值,则会抛出错误。

如果myMethod返回一个字符串,例如my name is bob,那么一旦$this->myMethod($this->args)执行,PHP将解析该值作为$this->_response()的参数,结果为:

return $this->_response('my name is bob');

在事件链之后,processAPI()方法将最终返回字符串JSON编码,这就是_response方法所做的。