2016-06-13 9 views
1

ポイントは私がgetDates()メソッドを持っていて、このメソッドの名前を文字列として取得したいが、このメソッドを実行しない。実際にはそれは次のように見えます:メソッド名を取得する方法PHPを呼び出す方法を知っている場合

$object->getResultExecutionMethod(convertmMethodNameToString($object->findDates())); 

getResultExecutionMethod($methodName) { 
    switch($methodName) { 
    case convertmMethodNameToString($this->findDates()): 
    return $getDatesStatus; 
    break; 

    case convertmMethodNameToString($this->anotherMethodOfThisClass()): 
    return $anotherMethodOfThisClassStatus; 
    break; 
    } 
} 

1クラス私はたくさんのメソッドを持っていて、このメソッドの実行ステータスに従う変数がたくさんあります。 convertmMethodNameToString()を呼び出して、私のメソッドをこのメソッドで実行状態にしたいと思っています。 convertmMethodNameToString()の機能はどうやって実装できますか?

+0

上で実行を参照してください。あなたはそれ他の方法で回避できますか? http://php.net/manual/en/functions.variable-functions.php –

+0

上記のコードでは、 'convertmMethodNameToString($ this-> findDates()'を '' findDates''に置き換えて、 'convertmMethodNameToString '$ this-> anotherMethodOfThisClass())'を '' anotherMethodOfThisClass''と置き換えます。 '' convertmMethodNameToString'関数はまったく必要ありません。 –

+0

@ mario-chuecaこのように使うのですか? '$ methodName =もし私がまだハードコードの各メソッド名に依存している; – Link

答えて

0

魔法の__callメソッドのメリットがあります。特定のメソッドのステータスが必要な場合は、同じ名前の接尾辞 "Status"を持つメソッドを呼び出すと言うことができます。いいところは、最後に "Status"を持つこれらのメソッドをすべて作成する必要はなく、トラップを使用できるということです。

また、__FUNCTION__を使用すると、実行中の関数の名前を取得できます。これはの場合はになりますが、の設定はになる可能性があります。

class myClass { 
    // Use an array to keep the statusses for each of the methods you have: 
    private $statusses = [ 
     "findDates" => "my original status", 
     "anotherMethodOfThisClass" => "another original status" 
    ]; 
    public function findDates($arg) { 
     echo "Executing " . __FUNCTION__ . ".\n"; 
     // Set execution status information: 
     $this->statusses[__FUNCTION__] = "last executed with argument = $arg"; 
    } 
    // ... other methods come here 

    // Finally: magic method to trap all undefined method calls (like a proxy): 
    public function __call($method, $arguments) { 
     // Remove the Status word at the end of the method name 
     $baseMethod = preg_replace("/Status$/", "", $method); 
     // ... and see if now we have an existing method. 
     if(method_exists($this, $baseMethod)) { 
      echo "Returning execution status for $baseMethod.\n"; 
      // Yes, so return the execution status we have in our array: 
      return $this->statusses[$baseMethod]; 
     } 
    } 
} 

// Create object 
$object = new myClass(); 
// Execute method 
$object->findDates("abc"); 
// Get execution status for that method. This method does not really exist, but it works 
$status = $object->findDatesStatus(); 
echo "Status: $status\n"; 

上記コード出力する:

実行findDatesここ

は、いくつかの例のコードです。
findDatesの実行ステータスを返します。
ステータス:最後の引数= ABC

で実行は、それがeval.in

+0

これはあなたの質問に答えましたか?あなたはコメントを残すことができますか? – trincot

関連する問題