2016-11-15 7 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-> endpoints($ this-> args)'という行は '$ this-> theValueOfTheEndpointVariable($ this-> args)'と同じです: '$ this-> myMethod($ this-> 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 URLによる方法。フレームワークではなく、私はこのチュートリアルをインターネットで見つけました。 –

答えて

2

PHPはvariable functionsvariable variablesの両方をサポートします。それはPHPがエンドポイントの変数を解決しますprocessApi

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

以内にあなたの声明に達すると

、私たちはあなたの例である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

それは良いです。ありがとう@マグヌスと@チャペル! –