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


How to access constant variables (defined in another file) dynamically in a function?

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

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

有什么想法吗?

http://php.net/constant

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

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

您想要constant()

constant($var); // value

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