【问题标题】:How to check if constant is defined, inside function - php如何检查是否在函数内部定义了常量 - php
【发布时间】:2017-01-03 09:59:49
【问题描述】:

我正在尝试制作一个小的 PHP 函数,它可以检查是否定义了一个常量,如果是,则回显它,如果没有,则回显空间或什么都没有。

现在,if(defined() 部分不起作用,因为常量正在被转移到函数内部的变量中。

function getConstant($constant) {  
  if(defined($constant)) {
    echo constant($constant);
  } else {
    echo '';
  }
}

echo constant($constant) 部分工作正常,但我无法检查该常量是否实际定义,因为它现在是一个变量。

我似乎找不到解决办法

【问题讨论】:

  • 你是什么意思常量被转移到一个变量?你是说常量的名字吗?
  • 一切正常3v4l.org/a8Rgh
  • $constant 必须是带有常量名称的字符串
  • 代码运行良好:- eval.in/708124
  • 如果 $constant 是一个字符串,您希望它具有常量字面量,那么代码就可以了。可能有命名空间问题?你在上课吗?

标签: php function variables constants


【解决方案1】:
public static function isConstants($constant) {
    $oClass = new ReflectionClass(__CLASS__);
    $allConstants = $oClass->getConstants();
    if (isset($allConstants[$constant])) {
       echo $allConstants[$constant];
    } else {
       echo '';
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-31
    • 2016-09-28
    • 2012-04-27
    • 1970-01-01
    • 2013-01-03
    • 1970-01-01
    • 2012-05-16
    • 2017-01-09
    相关资源
    最近更新 更多