php检查子类中的方法是否被覆盖 [英] php check if method overridden in child class
问题描述
是否可以检查方法是否已被PHP中的子类覆盖?
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
}
}
儿童班:
class bar extends foo {
public $goo;
public function createTable($data) {
// different code here
}
}
当遍历定义为此类成员的一组对象时,我该如何检查哪个对象具有新方法而不是旧方法?是否存在诸如method_overridden(mixed $object, string $method name)
之类的功能?
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);
}
我知道模板方法模式,但我想让程序的控件与类和方法本身分开.我需要诸如method_overridden
之类的功能来完成此任务.
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.
推荐答案
检查声明的类是否与对象的类匹配:
Check if the declaring class matches the class of the object:
$reflector = new \ReflectionMethod($ob, 'createTable');
$isProto = ($reflector->getDeclaringClass()->getName() !== get_class($ob));
PHP手册链接:
- ReflectionMethod
- ReflectionProperty
这篇关于php检查子类中的方法是否被覆盖的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!