Get the defining class for a constant in PHP

2020-04-27 00:06发布

问题:

I am wanting to use reflection to obtain a list of the constants defined by a class in PHP.

Currently using reflection I can get a list of the constants, but this also includes the ones declared in inherited classes. Is there a method I can use to either;

  • Given a class, get the constants defined by that class only
  • Given a constant and a class, check if that constant was defined by that class (not an inherited or extended parent).

For example, in the following code:

class Foo {
    const PARENT_CONST = 'parent';
    const ANOTHER_PARENT_CONST = 'another_parent';
}

class Bar extends Foo {
    const CHILD_CONST = 'child';
    const BAR_CONST = 'bar_const';
}

$reflection = new ReflectionClass('Bar');
print_r($reflection->getConstants());

The output is:

Array
(
    [CHILD_CONST] => child
    [BAR_CONST] => bar_const
    [PARENT_CONST] => parent
    [ANOTHER_PARENT_CONST] => another_parent
)

But I would like to have only this:

Array
(
    [CHILD_CONST] => child
    [BAR_CONST] => bar_const
)

回答1:

By default, PHP has no function I'm aware of that would already remove the parent classes and interfaces constants. So you would need to do that your own:

$reflection = new ReflectionClass('Bar');
$buffer = $reflection->getConstants();
foreach (
    array($reflection->getParentClass())
    + $reflection->getInterfaces()
    as $fill
) {
    $buffer = array_diff_key($buffer, $fill->getConstants());
}

The result in $buffer is the the array you are looking for:

Array
(
    [CHILD_CONST] => child
    [BAR_CONST] => bar_const
)