2016-11-15 186 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! –