如何使用 $variable 作为定义常量的名称访问 PHP 定义的常量


how to access php defined constant using a $variable as the name of the defined constant

我有一个使用 define() 定义的变量我想将该变量名称的一部分存储在常规的 php $variable中,然后通过动态设置名称来访问该定义的变量。即:

define('xxx_yyy',123);
$a='xxz';
$b='_yyy';

//How to I echo out "123" now?  (without using echo xxx_yyy);
//Something like these (don't work):
echo $a$b;
echo {$a$b};

我唯一能想到的是:

$defined=get_defined_vars();
echo $defined[$a$b];

但这似乎很笨拙

echo constant ( $a . $b );

是我认为您正在寻找的,因为它是一个常数。

您可以使用 constant()。 http://us3.php.net/manual/en/function.constant.php

它不是一个变量,而是一个常量:

echo constant ( $a . $b );

正确的函数是 get_defined_constants() 而不是 get_defined_vars()。

要使 123 回显出来,请使用以下命令:

echo $a . $b;

此外,define() 使常量不是变量。