마법의 __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
에서 실행을 참조하십시오? http://php.net/manual/en/functions.variable-functions.php –
위의 코드에서'convertmMethodNameToString ($ this-> findDates()'를''findDates''로 바꿀 수 있으며,'convertmMethodNameToString 'anotherMethodOfThisClass ''와 함께'$ this-> anotherMethodOfThisClass())'와'convertmMethodNameToString' 함수는 전혀 필요하지 않습니다. –
@ mario-chueca, 이런 식으로 사용 하시겠습니까? '$ methodName = 그렇다면 - 나는 여전히 각 메소드 이름을 하드 코드에 의존하고있다; – Link