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

Bro*_*and 130 php constants class-constants

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

class Profile {
    const LABEL_FIRST_NAME = "First Name";
    const LABEL_LAST_NAME = "Last Name";
    const LABEL_COMPANY_NAME = "Company";
}
Run Code Online (Sandbox Code Playgroud)

有没有办法获得在Profile课堂上定义的CONST列表?据我所知,最接近的选项(get_defined_constants())不会起作用.

我真正需要的是一个常量名称列表 - 如下所示:

array('LABEL_FIRST_NAME',
    'LABEL_LAST_NAME',
    'LABEL_COMPANY_NAME')
Run Code Online (Sandbox Code Playgroud)

要么:

array('Profile::LABEL_FIRST_NAME', 
    'Profile::LABEL_LAST_NAME',
    'Profile::LABEL_COMPANY_NAME')
Run Code Online (Sandbox Code Playgroud)

甚至:

array('Profile::LABEL_FIRST_NAME'=>'First Name', 
    'Profile::LABEL_LAST_NAME'=>'Last Name',
    'Profile::LABEL_COMPANY_NAME'=>'Company')
Run Code Online (Sandbox Code Playgroud)

Tom*_*igh 232

您可以使用Reflection进行此操作.请注意,如果您正在执行此操作,则可能需要查看缓存结果.

<?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());
Run Code Online (Sandbox Code Playgroud)

输出:

Array
(
    'LABEL_FIRST_NAME' => 'First Name',
    'LABEL_LAST_NAME' => 'Last Name',
    'LABEL_COMPANY_NAME' => 'Company'
)
Run Code Online (Sandbox Code Playgroud)

  • @Benji XVI在5.3如果你打开通知,你将无法使用没有引号的`Profile`,因为它会显示以下错误:注意:使用未定义的常量配置文件 - 假设'配置文件'.所以我建议保留引号''Profile' (11认同)
  • 最好在类中定义与常量相关的逻辑,因此您不需要对构造函数参数进行硬编码,而是使用`__CLASS__`. (10认同)
  • ```new ReflectionClass(Profile :: class)```也可以 (7认同)
  • 两个次要的NB:首先,在5.3中,`Profile`可以用作反射器构造函数的参数,没有引号(一个简单的类名); 第二,要完全清楚,结果数组的键是字符串,而不是常量,因为这里的格式可能会被建议.(值得一提的是,fn是[未记录](http://www.php.net/manual/en/reflectionclass.getconstants.php).) (4认同)

Wri*_*ken 21

这个

 $reflector = new ReflectionClass('Status');
 var_dump($reflector->getConstants());
Run Code Online (Sandbox Code Playgroud)

  • +1 就是这样,因为我找不到任何内置的过程 PHP 函数来获取类常量,这有点遗憾。 (2认同)

cle*_*tus 15

使用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";
}
?>
Run Code Online (Sandbox Code Playgroud)

输出:

LABEL_FIRST_NAME = "First Name"
LABEL_LAST_NAME = "Last Name"
LABEL_COMPANY_NAME = "Company"
Run Code Online (Sandbox Code Playgroud)

  • +1,尽管我想说这是使用其他海报提到的反射的绝佳时机,但了解“幕后”的工作原理并能够在没有它们的情况下进行工作或在必要时复制它们也很重要。不错的演出。 (3认同)

Par*_*ase 14

在PHP5中,您可以使用Reflection :( 手动参考)

$class = new ReflectionClass('Profile');
$consts = $class->getConstants();
Run Code Online (Sandbox Code Playgroud)


mwa*_*way 13

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

function GetClassConstants($sClassName) {
    $oClass = new ReflectionClass($sClassName);
    return $oClass->getConstants();
}
Run Code Online (Sandbox Code Playgroud)

来源就在这里.


Ben*_*mes 9

使用ReflectionClass并getConstants()准确提供您想要的内容:

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

输出:

Array
(
    [AAA] => 1
    [BBB] => 2
)
Run Code Online (Sandbox Code Playgroud)


Lui*_*uot 7

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

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());
Run Code Online (Sandbox Code Playgroud)


cha*_*aos 5

是的,您需要使用反射。看一下输出

<?
Reflection::export(new ReflectionClass('YourClass'));
?>
Run Code Online (Sandbox Code Playgroud)

那应该使您对所要看的东西有想法。


Dev*_*vWL 5

静态方法特质-营救

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

在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;

}
Run Code Online (Sandbox Code Playgroud)

使用范例

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

print_r($constList); // TEST
Run Code Online (Sandbox Code Playgroud)

输出:

Array
(
    [LABEL_FIRST_NAME] => First Name
    [LABEL_LAST_NAME] => Last Name
    [LABEL_COMPANY_NAME] => Company
)
Run Code Online (Sandbox Code Playgroud)