Get the defining class for a constant in PHP

ぐ巨炮叔叔 提交于 2019-12-31 04:10:53

问题


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
)


来源:https://stackoverflow.com/questions/11821137/get-the-defining-class-for-a-constant-in-php

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!