简体   繁体   中英

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM