简体   繁体   English

访问自类常量

[英]Access Self Class Constants

How can I access class constants within a function that is defined inside that class? 如何在该类内部定义的函数中访问类常量?

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
    }

}

I don't mean to access each constant but rather access ALL the constants in a form of array. 我并不是要访问每个常量,而是要以数组形式访问所有常量。 I saw something like: 我看到了类似的东西:

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

But what if I want to access ALL the list of constants inside that class? 但是,如果我想访问该类内部的所有常量列表怎么办?

To get a list of all the defined constants for a class, you'll need to use Reflection: 要获得一个类的所有已定义常量的列表,您需要使用Reflection:

The ReflectionClass object has a getConstants() method ReflectionClass对象具有getConstants()方法

If you want to collect all the constants as an array, you could use Reflection : 如果要将所有常量收集为数组,则可以使用Reflection

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

However, this would be very slow and mostly pointless. 但是,这将非常缓慢并且几乎没有意义。 What would be a much better idea, is to simply declare all of the constants in another array, which you then use: 更好的主意是简单地在另一个数组中声明所有常量,然后使用:

class Test{

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

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

}

This has the added advantage that it'll keep working if you add more constants. 这样做的另一个好处是,如果添加更多常量,它将继续工作。 There's no reason to assume all of a class' constants are related in any way, unless you explicitly make it so by defining the relation as an array. 除非您通过将关系定义为数组来明确地做到这一点,否则没有理由假定所有类的常量都以任何方式关联。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM