我有一个带有函数的基类,还有几个从基类派生的类。这些派生类中有一些重写该功能,有些则没有。
是否有一种方法可以检查某个特定的对象(该对象是已知的派生类之一)是否已覆盖该函数?
示例:
<?php
class BaseThing
{
function Bla() { echo "Hello, this is the base class\n"; }
}
class DerivedThing extends BaseThing
{
function Bla() { echo "Hello, this is a derived class\n"; }
}
class AnotherDerivedThing extends BaseThing
{
// Does not override Bla()
}
$a = new BaseThing();
$b = new DerivedThing();
$c = new AnotherDerivedThing();
$a->Bla(); // prints base class
$b->Bla(); // prints derived class
$c->Bla(); // prints base class
if (method_exists($b,'Bla')) echo "Method 'Bla' exists in DerivedThing\n";
if (method_exists($c,'Bla')) echo "Method 'Bla' exists in AnotherDerivedThing\n";
?>
[我尝试使用method_exists
,但显然它说$c
包含该方法,因为它是从包含该方法的类派生的。
是否可以检查对象是否覆盖特定功能?例如。在上面的示例中,我可以以某种方式检测到$b
确实覆盖了Bla()
函数,但是$c
没有吗?
您可以使用ReflectionClass::getMethod()并比较方法:
<?php
class BaseThing
{
function Bla() { echo "Hello, this is the base class\n"; }
}
class DerivedThing extends BaseThing
{
function Bla() { echo "Hello, this is a derived class\n"; }
}
class AnotherDerivedThing extends BaseThing
{
// Does not override Bla()
}
$reflectorBase = new ReflectionClass('BaseThing');
$reflectorDerived = new ReflectionClass('DerivedThing');
$reflectorAnotherDerived = new ReflectionClass('AnotherDerivedThing');
if ($reflectorBase->getMethod('Bla') == $reflectorDerived->getMethod('Bla'))
{
echo "methods are same in base and derived" . PHP_EOL;
}
else
{
echo "methods are NOT same in base and derived" . PHP_EOL;
}
if ($reflectorBase->getMethod('Bla') == $reflectorAnotherDerived->getMethod('Bla'))
{
echo "methods are same in base and derived 2" . PHP_EOL;
}
else
{
echo "methods are NOT same in base and derived 2" . PHP_EOL;
}
此输出:
methods are NOT same in base and derived
methods are same in base and derived 2