1

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

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

$type = 'FRUITS';

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

?>

apple, banana, orange

Fatal error: Access to undeclared static property: Food::$type

如何动态调用常量?

4

4 回答 4

4

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

echo constant('Food::' . $type);

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

于 2018-01-16T19:02:31.853 回答
1

ReflectionClass 可用于获取所有常量的数组,然后可以从那里找到特定常量的值:

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

$type = 'FRUITS';

$refClass = new ReflectionClass('Food');
$constants = $refClass->getConstants();

echo $constants[$type];

?>
于 2018-01-16T21:07:14.130 回答
0

使用命名空间时,请确保包含命名空间,即使它是自动加载的。

namespace YourNamespace;

class YourClass {
  public const HELLO = 'WORLD'; 
}

$yourConstant = 'HELLO';

// Not working
// >> PHP Warning:  constant(): Couldn't find constant YourClass::HELLO ..
constant('YourClass::' . $yourConstant);

// Working
constant('YourNamespace\YourClass::' . $yourConstant);```
于 2020-06-23T12:49:38.673 回答
0

您可以创建关联数组

class Constants{
  const Food = [
      "FRUITS " => 'apple, banana, orange',
      "VEGETABLES" => 'spinach, carrot, celery'
  ];
}

并像这样访问值

$type = "FRUITS";

echo Constants::Food[$type];
于 2020-07-01T04:49:28.250 回答