简体   繁体   中英

How to concatenate a string and a variable into a constant name?

I have a constant like define("EMPLOYEE_NAME_ID","employee"); and a variable $code = EMPLOYEE;

now i want to print like below

<?php echo $code.NAME_ID; ?>

But this prints only "EMPLOYEE_NAME_ID" and i want to print "employee". Then how to print this. The all over means is that i want to retriew variables from lang file.

A unquote string in PHP will be parsed as constant,
and if the constant is undefined,
it will treat as the string (instead of a variable)

If you dealing with constant, you can make use of constant function :-

echo constant("{$code}_NAME_ID");

However, use of this function will return warning message if the constant is not defined.
There are other option like parse_ini_file you can take a look,
this is ideal for handling large amount of setting / configuration

更好的方法是使用常数函数

echo constant($code."NAME_ID");
   define('VAR1', 'my var' );

   $var2 = 'hello';

   echo $var2.''.VAR1;  // period, two apostrophes, period

   // same as if you were doing:

   echo "some string ".$var2." some more string".VAR1;

One of the two is a constant, not a variable. You were attempting to use them like variable variables (oftentimes an array should be preferred in such circumstances).

You can however achieve the same effect with constants, using the constant() lookup function:

 <?php echo constant("{$code}_NAME_ID"); ?>

Note that you still need the extra _ underscore for this to work, which neither your constant suffix nor $code contained.

define("EMPLOYEE_NAME_ID","employee") is a constant so when combining it with a variable your syntax should be like this.

$temp = "John";

$var = EMPLOYEE_NAME_ID." : ".$temp;

echo $var; {Output : employee : john}

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