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

1 php variables constants

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

define_vars.php

<?

define("something","value");
define("something1","value");
define("something2","value");
define("something3","value");
Run Code Online (Sandbox Code Playgroud)

我有一个函数,它解析$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...

}
Run Code Online (Sandbox Code Playgroud)

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

有任何想法吗?

Nik*_*iko 5

http://php.net/constant

function something($var) {
    if (defined($var)) {
        $value = constant($var);
    }
}
Run Code Online (Sandbox Code Playgroud)

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