我知道有一个method_exists(),但即使继承了该方法,它也说是正确的。
class A
{
public function eix()
{
}
}
class B extends A
{
}
回声method_exists("B"、"eix");
所以这是真的,但B类没有。如何躲避?
您需要使用反射来实现此目的。 查看ReflectionMethod
类,您将找到getDeclaringClass
方法。
$classname = 'B';
$methodname = 'eix';
$method = new ReflectionMethod($classname, $methodname);
$declaringclass = $method->getDeclaringClass();
if ($classname == $declaringclass->name) {
// method was defined on the original class
}
也就是说,关键点是类B
确实有一个方法eix
,因为它继承了A
所有没有重新定义的方法。我无法完全确定您需要知道方法定义位置的情况,但是这种技术允许您在必要时这样做。
使用 get_parent_class() 标识父级
,然后使用 method_exists() 来标识父级。
echo method_exists (get_parent_class('B'), 'eix');
由于类 B 扩展了类 A,因此它固有了它的所有方法,method_exists()
将始终返回 true。
问题是为什么您需要知道该方法首先是在类 A 还是类 B 中创建的?我认为没有理由需要这些信息。
如果这是一个问题,您可能应该从一开始就重新考虑您的架构设计。
但正如 Mark Baker 所解释的那样,人们可能会发现至少该方法是否也存在于父类中,并不一定意味着它没有在子类中被覆盖。
if(method_exists(get_parent_class('B'), 'eix'))
{
//Exist in parent class and was not first created in this.
//But still is inherent to this.
}
else
{
//Doesn't exist in parent and must been created in this.
}