Как проверить, переопределена ли функция в производном классе? - PullRequest
2 голосов
/ 16 марта 2020

У меня есть базовый класс с функцией и несколько классов, производных от базового класса. Некоторые из этих производных классов переопределяют функцию, некоторые нет.

Есть ли способ проверить, переопределил ли конкретный объект, который, как известно, является одним из производных классов, эту функцию?

Пример:

<?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 - нет?

Ответы [ 2 ]

1 голос
/ 16 марта 2020

Снова используя отражение (как упоминалось в deceze), вы можете получить метод и проверить, в каком классе он объявлен ...

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()
}

$reflectorDerived = new ReflectionClass('DerivedThing');
$method = $reflectorDerived->getMethod("Bla");
echo $method->getDeclaringClass()->name.PHP_EOL;

$reflectorAnotherDerived = new ReflectionClass('AnotherDerivedThing');
$method = $reflectorAnotherDerived->getMethod("Bla");
echo $method->getDeclaringClass()->name;

дает ..

DerivedThing
BaseThing
1 голос
/ 16 марта 2020

Вы можете использовать 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
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...