【问题标题】:Dynamic constant name in PHPPHP中的动态常量名
【发布时间】:2011-04-29 01:18:33
【问题描述】:

我正在尝试动态创建一个常量名称,然后获取该值。

define( CONSTANT_1 , "Some value" ) ;

// try to use it dynamically ...
$constant_number = 1 ;
$constant_name = ("CONSTANT_" . $constant_number) ;

// try to assign the constant value to a variable...
$constant_value = $constant_name;

但我发现 $constant 值仍然包含常量的名称,而不是值。

我也尝试了第二级间接$$constant_name 但这会使它成为变量而不是常量。

有人可以解释一下吗?

【问题讨论】:

    标签: php constants indirection


    【解决方案1】:

    http://dk.php.net/manual/en/function.constant.php

    echo constant($constant_name);
    

    【讨论】:

      【解决方案2】:

      并证明这也适用于类常量:

      class Joshua {
          const SAY_HELLO = "Hello, World";
      }
      
      $command = "HELLO";
      echo constant("Joshua::SAY_$command");
      

      【讨论】:

      • 值得注意的是,如果常量位于不在当前命名空间中的类中,您可能需要指定完全限定(命名空间)类名 - 无论您是否添加了“使用”文件中的类。
      • 这个答案很好,因为有很好的例子。这正是我想要的:) 谢谢!
      • @loplateral ::class 常量可用于检索完全限定的命名空间,例如:constant(YourClass::class . '::CONSTANT_' . $yourVariable);
      • 请注意,::class keyword 自 php 5.5 起可用
      【解决方案3】:

      要在你的类中使用动态常量名,你可以使用反射特性(从 php5 开始):

      $thisClass = new ReflectionClass(__CLASS__);
      $thisClass->getConstant($constName);
      

      例如: 如果您只想过滤类中的特定 (SORT_*) 常量

      class MyClass 
      {
          const SORT_RELEVANCE = 1;
          const SORT_STARTDATE = 2;
      
          const DISTANCE_DEFAULT = 20;
      
          public static function getAvailableSortDirections()
          {
              $thisClass = new ReflectionClass(__CLASS__);
              $classConstants = array_keys($thisClass->getConstants());
      
              $sortDirections = [];
              foreach ($classConstants as $constName) {
                  if (0 === strpos($constName, 'SORT_')) {
                      $sortDirections[] =  $thisClass->getConstant($constName);
                  }
              }
      
              return $sortDirections;
          }
      }
      
      var_dump(MyClass::getAvailableSortDirections());
      

      结果:

      array (size=2)
        0 => int 1
        1 => int 2
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-06-25
        • 2017-07-07
        • 1970-01-01
        相关资源
        最近更新 更多