2013-05-13 3 views
4

PHP를 사용하면 클래스가 메소드를 오버라이드 한 클래스를 어떻게 판별 할 수 있습니까?PHP 하위 클래스가 수퍼 클래스의 메서드를 재정의했는지 확인하는 방법?

주어진 다음의 두 클래스 :

하는 방법이 그 방법에 따라 다른 작업을 수행 할 것이다 슈퍼 클래스에 추가 할 수있는 방법
class Superclass { 
    protected function doFoo($data) { 
     // empty 
    } 

    protected function doBar($data) { 
     // empty 
    } 
} 

class Subclass extends Superclass { 
    protected function doFoo($data) { 
     // do something 
    } 
} 

이 무시되어왔다? 예를 들어

: ReflectionMethod::getPrototype 함께

if ([doFoo is overridden]) { 
    // Perform an action without calling doFoo 
} 
if ([doBar is overridden]) { 
    // Perform an action without calling doBar 
} 
+0

@schleis 예제는 약간 인위적이었습니다. 지금은 기존 클래스의 구조에서 가져올 수있는 HTTP를 통해 일부 정보를 노출해야합니다. – Andrew

답변

9

.

$foo = new \ReflectionMethod('Subclass', 'doFoo'); 

$declaringClass = $foo->getDeclaringClass()->getName(); 
$proto = $foo->getPrototype(); 

if($proto && $proto->getDeclaringClass()->getName() !== $declaringClass){ 
    // overridden 
} 

클래스가 일치하면 오버라이드되지 않으며, 그렇지 않은 경우 오버라이드되지 않습니다.


또는 두 클래스 이름을 모두 알고 있다면 간단히 $declaringClass을 다른 클래스 이름과 비교하십시오.

+0

좋은 답변 otp – Drew

관련 문제