简体   繁体   English

PHP:变量中的常量名称

[英]PHP: Constant name from a variable

I have a PHP class that looks like this 我有一个看起来像这样的PHP类

class Painter {
    const COLOR_PHYSIC = 'brown';
    const COLOR_PSYCHIC = 'purple';
    const COLOR_ATTACKER = 'dodgerblue';
    const COLOR_DEFENDER = 'darkorange';

    public function __call($name, $arguments) {
        if(defined('self::'.$name)) $name = self::$$name;

        return '<span class="'.$name.'">'.$arguments[0].'</span>';
    }
}

Which returns a colored html representation of a string. 返回字符串的彩色html表示形式。 Example usage: 用法示例:

$painter->red('Text'); // <span class="red">Text</span>

I would also like to have some preset colors that could be changed in future, if such necessity is present, which is where I am stuck. 我还希望有一些可以在将来更改的预设颜色,如果需要的话,这就是我要坚持的地方。

if I run this line 如果我跑这条线

$painter->COLOR_DEFENDER('Text');

I get the error message 我收到错误消息

Access to undeclared static property: Painter::$COLOR_DEFENDER 访问未声明的静态属性:Painter :: $ COLOR_DEFENDER

How can I modify the code so that $name can be as well interpreted as a constant? 如何修改代码,以便可以将$name解释为常量?

Also on a side note, I am curious to find out, if I were to change the method of storing preset colors to an array instead of constants, would that use less memory? 另外,我很想知道,如果我要更改将预设颜色存储到数组而不是常量的方法,那会不会使用更少的内存? I'd be really happy if someone more familiar with under-the-hood PHP can answer this question. 如果更熟悉幕后PHP的人可以回答这个问题,我将非常高兴。 Thanks in advance! 提前致谢!

if (defined('self::' . $name)) {
    $name = constant('self::' . $name);
}

To dynamically retrieve constants, you need to use the constant function . 要动态检索常量,您需要使用constant函数

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

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