如何在函数中动态访问常量变量(在另一个文件中定义)?

时间:2012-03-30 21:18:49

标签: php variables constants

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

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

任何想法?

3 个答案:

答案 0 :(得分:5)

http://php.net/constant

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

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

答案 1 :(得分:4)

您想要constant()

constant($var); // value

答案 2 :(得分:2)

使用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);
}