【问题标题】:Access Class Constants Dynamically in PHP在 PHP 中动态访问类常量
【发布时间】:2018-06-25 13:19:29
【问题描述】:

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

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

如何动态调用常量?

【问题讨论】:

  • 我想你不能。

标签: php constants class-constants


【解决方案1】:

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

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

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

【讨论】:

  • 是的。使用 ReflectionClass 获取所有常量的数组是另一种以编程方式查找值的方法。我希望有一些晦涩的语法可以通过单个语句/动作来获取值。
【解决方案2】:

一个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];

?>

【讨论】:

    【解决方案3】:

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

    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);```
    

    【讨论】:

      【解决方案4】:

      你可以创建关联数组

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

      并像这样访问值

      $type = "FRUITS";
      
      echo Constants::Food[$type];
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-09-17
        • 1970-01-01
        • 2019-01-18
        • 1970-01-01
        • 1970-01-01
        • 2012-02-12
        相关资源
        最近更新 更多