在 PHP 中动态访问类常量

jcr*_*opp 2 php constants class-constants

我希望能够动态查找常量的值,但使用变量不适用于语法。

<?php
class Food {
    const FRUITS = 'apple, banana, orange';
    const VEGETABLES = 'spinach, carrot, celery';
}

$type = 'FRUITS';

echo Food::FRUITS;
echo Food::$type;

?>
Run Code Online (Sandbox Code Playgroud)

给出

apple, banana, orange

Fatal error: Access to undeclared static property: Food::$type
Run Code Online (Sandbox Code Playgroud)

如何动态调用常量?

u_m*_*der 9

我想到的唯一解决方案是使用constant函数

echo constant('Food::' . $type);
Run Code Online (Sandbox Code Playgroud)

在这里,您创建一个常量(包括类)的名称作为字符串,并将该字符串 ( 'Food::FRUITS') 传递给constant函数。