php检查是否在子类中重写了方法

时间:2013-07-15 20:21:32

标签: php oop overloading

是否可以检查PHP中的子类是否已覆盖某个方法?

<!-- language: lang-php -->

class foo {
    protected $url;
    protected $name;
    protected $id;

    var $baz;

    function __construct($name, $id, $url) {
        $this->name = $name;
        $this->id = $id;
        $this->url = $url;
    }

    function createTable($data) {
        // do default actions
    }
}

儿童班:

class bar extends foo {
    public $goo;

    public function createTable($data) {
        // different code here
    }
}

当迭代定义为此类成员的对象数组时,如何检查哪个对象具有新方法而不是旧方法?是否存在method_overridden(mixed $object, string $method name)等函数?

foreach ($objects as $ob) {
    if (method_overridden($ob, "createTable")) {
        // stuff that should only happen if this method is overridden
    }
    $ob->createTable($dataset);
}

我知道template method pattern,但是我想说我希望程序的控制与类和方法本身分开。我需要一个像method_overridden这样的函数来完成这个。

2 个答案:

答案 0 :(得分:20)

检查声明类是否与对象的类匹配:

$reflector = new \ReflectionMethod($ob, 'createTable');
$isProto = ($reflector->getDeclaringClass()->getName() !== get_class($ob));

答案 1 :(得分:2)

要获取此信息,您必须使用ReflectionClass。您可以尝试使用getMethod并检查方法的类名。

$class = new ReflectionClass($this);
$method = $class->getMethod("yourMethod");
if ($method->class == 'classname') {
    //.. do something
}

但请记住,反射速度不是很快,所以要小心使用。