gpt4 book ai didi

php - 使用 constant() 函数和直接通过名称引用常量有什么区别?

转载 作者:可可西里 更新时间:2023-11-01 00:02:37 24 4
gpt4 key购买 nike

AS per PHP manual constant() 如果您需要检索常量的值但不知道其名称,则很有用。 IE。它存储在变量中或由函数返回。

define("MAXSIZE", 100);

echo MAXSIZE;
echo constant("MAXSIZE"); // same thing as the previous line

如果有人不知道 MAXSIZE ,他怎么能使用 constant("MAXSIZE")。这足以使用 echo MAXSIZE 吗?有人可以举例说明吗?我尝试了以下代码,但它不起作用。

    define("MAXSIZE", 100);

$x = MAXSIZE;
echo constant($x);

最佳答案

试试这个,应该可以工作

define("MAXSIZE", 100);

$x = "MAXSIZE";
echo constant($x);

constant() 方法将返回定义常量的值,如果您有它的字符串变量的话。

考虑这个例子。

define("MAX", 1000);
define("MIN", 1);

$val = 50;
$const = null;
if ( $val < 50 ) {
$const = "MAX";
} else {
$const = "MIN";
}

echo constant($const); // output 1

关于php - 使用 constant() 函数和直接通过名称引用常量有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22034609/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com