[英]Can I pass a DEFINED constant to a function through a variable in PHP?
I have the following code: 我有以下代码:
DEFINE('DEFINEDTESTVAR', 'Hello World');
function callit($callVar) {
echo "The call is ".$callVar;
}
$passthis = 'DEFINEDTESTVAR';
callit($passthis);
I know I can do callit(DEFINEDTESTVAR)
but that's not what I am looking to do. 我知道我可以执行
callit(DEFINEDTESTVAR)
但这不是我想要的。 Is it possible? 可能吗?
Either pass the constant itself: 要么传递常量本身:
$passthis = DEFINEDTESTVAR;
Or access it through constant()
which allows you to test for null in case it isn't defined (for undefined constants, passing the constant literally results in a string with the constant name): 或通过
constant()
访问它,如果未定义它,则可以测试null(对于未定义的常数,按字面传递常数会导致产生一个具有常数名称的字符串):
$passthis = constant('DEFINEDTESTVAR');
define('DEFINEDTESTVAR', 'Hello World'); // you should use define
function callit($callVar) {
echo "The call is ".$callVar;
}
$passthis = DEFINEDTESTVAR; // no need to use quotes
callit($passthis);
You can get a constant's value from a string with constant(). 您可以使用constant()从字符串中获取常量的值。 It will return null if the named constant is not found.
如果找不到命名常量,它将返回null。
$passthis = constant('DEFINEDTESTVAR');
callit($passthis);
<?php
DEFINE('DEFINEDTESTVAR', 'Hello World');
function callit($callVar) {
echo "The call is ".$callVar;
}
$passthis = DEFINEDTESTVAR;
callit($passthis);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.