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. 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):
$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(). It will return null if the named constant is not found.
$passthis = constant('DEFINEDTESTVAR');
callit($passthis);
<?php
DEFINE('DEFINEDTESTVAR', 'Hello World');
function callit($callVar) {
echo "The call is ".$callVar;
}
$passthis = DEFINEDTESTVAR;
callit($passthis);
精彩评论