简体   繁体   中英

PHP: Constant name from a variable

I have a PHP class that looks like this

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. 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

How can I modify the code so that $name can be as well interpreted as a constant?

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. Thanks in advance!

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

To dynamically retrieve constants, you need to use the constant function .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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