0

我知道有一个 method_exists() 但即使该方法被继承它也说是真的。

class A
{
 public function eix()
 {
 }
}

class B extends A
{
}

echo method_exists ('B', 'eix');

所以它是真的,但B级没有它。如何躲避这个?

4

3 回答 3

3

您需要使用反射来实现这一点。查看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它没有重新定义的方法。我无法完全确定您需要知道方法在哪里定义的情况,但是这种技术允许您在必要时这样做。

于 2012-05-08T12:04:35.217 回答
3

使用get_parent_class()来识别父级,然后使用 method_exists() 反对它。

echo method_exists (get_parent_class('B'), 'eix');
于 2012-05-08T12:05:09.633 回答
0

由于 B 类扩展了 A 类,因此它固有其所有方法,并且method_exists()始终返回 true。

问题是为什么您需要知道该方法是首先在 A 类还是 B 类中创建的?我认为没有理由需要这些信息。

如果这是一个问题,您可能应该从一开始就重新考虑您的架构设计。

但正如马克贝克解释的那样,至少可以发现该方法是否也存在于父类中,并不一定意味着它没有在子类中被覆盖。

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.
}
于 2012-05-08T12:29:24.830 回答