【问题标题】:How to access constant variables (defined in another file) dynamically in a function?如何在函数中动态访问常量变量(在另一个文件中定义)?
【发布时间】:2012-03-30 21:18:48
【问题描述】:

我有一个定义常量变量的文件,如下所示:

define_vars.php

<?

define("something","value");
define("something1","value");
define("something2","value");
define("something3","value");

我有一个函数将$var 解析为常量变量名,如下所示:

function something($var=''){

include('define_vars.php');

// $var is the name of one of the variables I am defining in the other file (define_vars.php)
// So $var may have a value of "something3", which is the name of one of the constants defined in the other file...

}

我需要以某种方式获取常量的值,当 $var 保存我希望获取的值的常量的名称时......有意义吗? :S

有什么想法吗?

【问题讨论】:

    标签: php variables constants


    【解决方案1】:

    http://php.net/constant

    function something($var) {
        if (defined($var)) {
            $value = constant($var);
        }
    }
    

    您还应确保包含定义的文件仅包含一次,因此请改用require_once('define_vars.php');

    【讨论】:

      【解决方案2】:

      你想要constant()

      constant($var); // value
      

      【讨论】:

        【解决方案3】:

        使用constant() 获取值。你可以这样做

        function something($var = '') {
            include_once('define_vars.php'); //you don't want to include the file more than once or it will cause a fatal error when trying to redefine your constants
            return (defined($var) ? constant($var) : null);
        }
        

        【讨论】:

          猜你喜欢
          • 2021-12-24
          • 1970-01-01
          • 2012-07-31
          • 2023-03-20
          • 2013-10-27
          • 2019-05-10
          • 2019-10-29
          • 1970-01-01
          • 2022-12-06
          相关资源
          最近更新 更多