【问题标题】:Get a constant value from a string in PHP [duplicate]从PHP中的字符串获取常量值[重复]
【发布时间】:2018-02-04 07:24:11
【问题描述】:

我需要从字符串中提取 PHP 中常量的值。 我的例子比我的话更能解释它:)

常量.php:

define('CONNECTION_FAILED', 'Connection Error');

index.php:

include_once 'constants.php';
$success = $_GET['message']; //$success -> "CONNECTION_FAILED"

现在我要做的是用 $success 变量上的名称显示常量的值。

你知道做这件简单事情的方法吗?

提前谢谢你

【问题讨论】:

    标签: php


    【解决方案1】:

    您可以使用constant 函数来获取常量的值:

    define("MAXSIZE", 100);
    
    echo MAXSIZE;
    echo constant("MAXSIZE"); // same thing as the previous line
    

    在你的情况下,它可以是:

    echo constant($success);
    

    【讨论】:

      【解决方案2】:

      是的,您可以使用常量函数获取计算名称的常量的值:

      define('CONNECTION_FAILED', 'Connection Error');
      $success = $_GET['message']; //$success -> 'CONNECTION_FAILED'
      $message = constant($success); // 'Connection error'
      

      【讨论】:

        【解决方案3】:

        constanthttp://dk.php.net/manual/en/function.constant.php 你可以constant($success)

        【讨论】:

          【解决方案4】:

          使用constant(),你可以实现你想要的。在你做任何事情之前检查它的设置以避免出现未定义的常量通知。

          include_once 'constants.php';
          $success = '';
          if (isset($_GET['message']) && constant($_GET['message']) !== null) {
              $success = constant($_GET['message']);
          } else {
              // Not a valid message
              // $_GET['message'] not defined as a constant's name
          }
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 2011-05-14
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2014-02-10
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多