Php 访问自类常量

Php 访问自类常量,php,class,constants,Php,Class,Constants,如何访问在该类中定义的函数中的类常量 class Test{ const STATUS_ENABLED = 'Enabled'; const STATUS_DISABLED = 'Disabled'; public function someMethod(){ //how can I access ALL the constants here let's say in a form of array } } 我的意思不是访问每个常量,而是以

如何访问在该类中定义的函数中的类常量

class Test{

    const STATUS_ENABLED = 'Enabled';
    const STATUS_DISABLED = 'Disabled';

    public function someMethod(){
        //how can I access ALL the constants here let's say in a form of array
    }

}
我的意思不是访问每个常量,而是以数组的形式访问所有常量。我看到的是:

<?php
class Profile {
    const LABEL_FIRST_NAME = "First Name";
    const LABEL_LAST_NAME = "Last Name";
    const LABEL_COMPANY_NAME = "Company";
}


$refl = new ReflectionClass('Profile');
print_r($refl->getConstants());

要获取类的所有已定义常量的列表,需要使用反射:


对象有一个方法

如果要将所有常量收集为一个数组,可以使用:

然而,这将非常缓慢,而且几乎毫无意义。更好的方法是简单地声明另一个数组中的所有常量,然后使用:

class Test{

    const STATUS_ENABLED = 'Enabled';
    const STATUS_DISABLED = 'Disabled';

    $states = array(
      self::STATUS_ENABLED,
      self::STATUS_DISABLED,

}

这样做的另一个好处是,如果添加更多常量,它将继续工作。没有理由假设一个类的所有常量都是以任何方式相关的,除非您通过将关系定义为数组来明确地这样做。

好的,现在您已经编辑了您的问题,因为我们中的一些人提到了反射的getConstants()方法,说您已经在使用getConstants()。。。。所以,解释一下你的电脑有什么问题,因为它看起来就像你要的一样-。
class Test{

    const STATUS_ENABLED = 'Enabled';
    const STATUS_DISABLED = 'Disabled';

    $states = array(
      self::STATUS_ENABLED,
      self::STATUS_DISABLED,

}