【问题标题】:Access Self Class Constants访问自身类常量
【发布时间】:2015-04-07 08:00:42
【问题描述】:

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

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

但是如果我想访问该类中的所有常量列表呢?

【问题讨论】:

  • 好的,你已经编辑了你的问题,因为我们中的一些人已经提到了 Reflection 的 getConstants() 方法,说你已经在使用 getConstants() ......所以解释一下你有什么问题重新使用它,因为它看起来完全符合您的要求 - Demo

标签: php class constants


【解决方案1】:

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

ReflectionClass 对象有一个getConstants() 方法

【讨论】:

    【解决方案2】:

    如果你想把所有的常量收集成一个数组,你可以使用Reflection:

    $reflection = new ReflectionClass("classNameGoesHere");
    $reflection->getConstants();
    

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

    class Test{
    
        const STATUS_ENABLED = 'Enabled';
        const STATUS_DISABLED = 'Disabled';
    
        $states = array(
          self::STATUS_ENABLED,
          self::STATUS_DISABLED,
    
    }
    

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

    【讨论】:

      猜你喜欢
      • 2011-09-19
      • 1970-01-01
      • 2013-01-29
      • 1970-01-01
      • 2013-08-23
      • 1970-01-01
      • 2013-11-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多