2016-06-13 2 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 'anotherMethodOfThisClass ''와 함께'$ this-> anotherMethodOfThisClass())'와'convertmMethodNameToString' 함수는 전혀 필요하지 않습니다. –

+0

@ mario-chueca, 이런 식으로 사용 하시겠습니까? '$ methodName = 그렇다면 - 나는 여전히 각 메소드 이름을 하드 코드에 의존하고있다; – Link

답변

0

마법의 __call 방법을 사용하면 도움이 될 것입니다. 특정 메서드에 대한 상태가 필요한 경우 동일한 이름의 메서드를 호출 할 수 있지만 "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

관련 문제