我可以在 PHP 类上定义 CONST 吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/956401/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 00:27:59  来源:igfitidea点击:

Can I get CONST's defined on a PHP class?

phpconstantsclass-constants

提问by Brock Boland

I have several CONST's defined on some classes, and want to get a list of them. For example:

我在某些类上定义了几个 CONST,并希望获得它们的列表。例如:

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

Is there any way to get a list of the CONST's defined on the Profileclass? As far as I can tell, the closest option(get_defined_constants()) won't do the trick.

有没有办法获得Profile类上定义的 CONST 的列表?据我所知,最接近的 option( get_defined_constants()) 不起作用。

What I actually need is a list of the constant names - something like this:

我真正需要的是一个常量名称列表 - 像这样:

array('LABEL_FIRST_NAME',
    'LABEL_LAST_NAME',
    'LABEL_COMPANY_NAME')

Or:

或者:

array('Profile::LABEL_FIRST_NAME', 
    'Profile::LABEL_LAST_NAME',
    'Profile::LABEL_COMPANY_NAME')

Or even:

甚至:

array('Profile::LABEL_FIRST_NAME'=>'First Name', 
    'Profile::LABEL_LAST_NAME'=>'Last Name',
    'Profile::LABEL_COMPANY_NAME'=>'Company')

回答by Tom Haigh

You can use Reflectionfor this. Note that if you are doing this a lot you may want to looking at caching the result.

您可以为此使用反射。请注意,如果您经常这样做,您可能需要查看缓存结果。

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

Output:

输出:

Array
(
    'LABEL_FIRST_NAME' => 'First Name',
    'LABEL_LAST_NAME' => 'Last Name',
    'LABEL_COMPANY_NAME' => 'Company'
)

回答by Wrikken

This

这个

 $reflector = new ReflectionClass('Status');
 var_dump($reflector->getConstants());

回答by cletus

Use token_get_all(). Namely:

使用token_get_all()。即:

<?php
header('Content-Type: text/plain');

$file = file_get_contents('Profile.php');
$tokens = token_get_all($file);

$const = false;
$name = '';
$constants = array();
foreach ($tokens as $token) {
    if (is_array($token)) {
        if ($token[0] != T_WHITESPACE) {
            if ($token[0] == T_CONST && $token[1] == 'const') {
                $const = true;
                $name = '';
            } else if ($token[0] == T_STRING && $const) {
                $const = false;
                $name = $token[1];
            } else if ($token[0] == T_CONSTANT_ENCAPSED_STRING && $name) {
                $constants[$name] = $token[1];
                $name = '';
            }
        }
    } else if ($token != '=') {
        $const = false;
        $name = '';
    }
}

foreach ($constants as $constant => $value) {
    echo "$constant = $value\n";
}
?>

Output:

输出:

LABEL_FIRST_NAME = "First Name"
LABEL_LAST_NAME = "Last Name"
LABEL_COMPANY_NAME = "Company"

回答by Parsingphase

In PHP5 you can use Reflection: (manual reference)

在 PHP5 中你可以使用 Reflection: (manual reference)

$class = new ReflectionClass('Profile');
$consts = $class->getConstants();

回答by mway

Per the PHP docs comments, if you're able to use the ReflectionClass (PHP 5):

根据 PHP 文档注释,如果您能够使用 ReflectionClass (PHP 5):

function GetClassConstants($sClassName) {
    $oClass = new ReflectionClass($sClassName);
    return $oClass->getConstants();
}

Source is here.

来源在这里。

回答by Ben James

Using ReflectionClass and getConstants()gives exactly what you want:

使用 ReflectionClass 并getConstants()给出你想要的:

<?php
class Cl {
    const AAA = 1;
    const BBB = 2;
}
$r = new ReflectionClass('Cl');
print_r($r->getConstants());

Output:

输出:

Array
(
    [AAA] => 1
    [BBB] => 2
)

回答by DevWL

Trait with static method - to the rescue

静态方法的特性 - 拯救

Looks like it is a nice place to use Traits with a static function to extend class functionality. Traits will also let us implement this functionality in any other class without rewriting the same code over and over again (stay DRY).

看起来这是一个使用 Traits 和静态函数来扩展类功能的好地方。Traits 还可以让我们在任何其他类中实现此功能,而无需一遍又一遍地重写相同的代码(保持 DRY)。

Use our custom 'ConstantExport' Trait with in Profile class. Do it for every class that you need this functionality.

在 Profile 类中使用我们自定义的“ConstantExport”特性。为您需要此功能的每个类执行此操作。

/**
 * ConstantExport Trait implements getConstants() method which allows 
 * to return class constant as an assosiative array
 */
Trait ConstantExport 
{
    /**
     * @return [const_name => 'value', ...]
     */
    static function getConstants(){
        $refl = new \ReflectionClass(__CLASS__);
        return $refl->getConstants();
    }
}

Class Profile 
{
    const LABEL_FIRST_NAME = "First Name";
    const LABEL_LAST_NAME = "Last Name";
    const LABEL_COMPANY_NAME = "Company";

    use ConstantExport;

}

USE EXAMPLE

使用示例

// So simple and so clean
$constList = Profile::getConstants(); 

print_r($constList); // TEST

OUTPUTS:

输出:

Array
(
    [LABEL_FIRST_NAME] => First Name
    [LABEL_LAST_NAME] => Last Name
    [LABEL_COMPANY_NAME] => Company
)

回答by chaos

Yeah, you use reflection. Look at the output of

是的,你使用反射。看看输出

<?
Reflection::export(new ReflectionClass('YourClass'));
?>

That should give you the idea of what you'll be looking at.

这应该让您了解您将要查看的内容。

回答by Luis Siquot

It is handy to have a method inside the class to return its own constants.
You can do this way:

在类中有一个方法来返回它自己的常量是很方便的。
你可以这样做:

class Profile {
    const LABEL_FIRST_NAME = "First Name";
    const LABEL_LAST_NAME = "Last Name";
    const LABEL_COMPANY_NAME = "Company";


    public static function getAllConsts() {
        return (new ReflectionClass(get_class()))->getConstants();
    }
}

// test
print_r(Profile::getAllConsts());

回答by revoke

Eventually with namespaces:

最终使用命名空间:

namespaces enums;
class enumCountries 
{
  const CountryAustria          = 1 ;
  const CountrySweden           = 24;
  const CountryUnitedKingdom    = 25;
}


namespace Helpers;
class Helpers
{
  static function getCountries()
  {
    $c = new \ReflectionClass('\enums\enumCountries');
    return $c->getConstants();
  }
}


print_r(\Helpers\Helpers::getCountries());