php check if method overridden in child class

情到浓时终转凉″ 提交于 2019-12-12 09:32:09

问题


Is it possible to check whether or not a method has been overridden by a child class in 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
    }
}

Child class:

class bar extends foo {
    public $goo;

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

When iterating through an array of objects defined as members of this class, how can I check which of the objects has the new method as opposed to the old one? Does a function such as method_overridden(mixed $object, string $method name) exist?

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

I am aware of the template method pattern, but let's say I want the control of the program to be separate from the class and the methods themselves. I would need a function such as method_overridden to accomplish this.


回答1:


Check if the declaring class matches the class of the object:

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

PHP Manual links:

  • ReflectionMethod
  • ReflectionProperty



回答2:


To get this information, you have to use ReflectionClass. You could try getMethod and check the class name of the method.

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

But keep in mind, that reflection isn't very fast, so be careful with usage.



来源:https://stackoverflow.com/questions/17663178/php-check-if-method-overridden-in-child-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!