2016-11-15 185 views
0

我不知道问题(我问的方式)是否正确。我接受你的建议。我想知道下面的代码是如何工作的。如果你想要我可以提供的任何细节,我想要的。一个函数返回另一个函数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)); 
+0

你通过该方法如何?我只能看到班级的内部,而不是你如何使用它。这是什么课程?框架? $ this-> {$ this-> endpoint}($ this-> args)'与$ this-> theValueOfTheEndpointVariable($ this-> args)'相同,在你的情况下:'$ this-> myMethod的($这个 - > ARG)'。 –

+0

PHP支持[变量函数](http://php.net/manual/en/functions.variable-functions.php)。你的端点周围的花括号告诉PHP在使用它作为变量之前解析该值。参见[PHP变量变量](http://php.net/manual/en/language.variables.variable.php) –

+0

@magnus I pass方法由url。不是我在互联网上找到这个教程的框架。 –

回答

2

PHP同时支持variable functionsvariable variables

当它到达内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方法所做的。

+0

很难解释它比这更好。 :) –

+0

这样比较好。谢谢@magnus和@chappell! –