gpt4 book ai didi

php - 如何检查函数是否在派生类中被覆盖?

转载 作者:行者123 更新时间:2023-12-04 10:24:04 24 4
gpt4 key购买 nike

我有一个带有函数的基类,以及从基类派生的几个类。其中一些派生类覆盖了该函数,有些则没有。

有没有办法检查已知是派生类之一的特定对象是否覆盖了该函数?

例子:

<?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 the same in base and derived" . PHP_EOL;
}
else
{
echo "methods are NOT the same in base and derived" . PHP_EOL;
}

if ($reflectorBase->getMethod('Bla') == $reflectorAnotherDerived->getMethod('Bla'))
{
echo "methods are the same in base and derived 2" . PHP_EOL;
}
else
{
echo "methods are NOT the same in base and derived 2" . PHP_EOL;
}

这输出:
methods are NOT the same in base and derived
methods are the same in base and derived 2

关于php - 如何检查函数是否在派生类中被覆盖?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60704331/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com