문제

I want to use a constant in PHP, but I also want to put it inside double quotes like a variable. Is this at all possible?

define("TESTER", "World!");
echo "Hello, TESTER";

obviously outputs "Hello, TESTER", but what I really want is something like:

$tester = "World!";
echo "Hello, $tester";

outputs "Hello, World!".

도움이 되었습니까?

해결책

Sorry, that's not the way constants in PHP work. You can put variables in double quotes and heredocs but not constants.

다른 팁

I recomend you to use concatenation because:

  1. When you use a variable into a double quotes string your visibility is not good;
  2. When you use a double quotes string the php can to process slowly;
  3. You don't use a constant into a string, because don't have any delimiter to the php knows what is the constant.

Concatenation is the way to go.

Unless you want the hokey, nasty, inefficient, evil monkey way of:

echo preg_replace("/TESTER/",TESTER,$original_content);

no way, unless you write your own string parsing function

I've found that when dot-concatenation of a constant is a problem, using sprintf to get my string is usually the way I want to go in the end.

Alternatively, do

"this is " . MY_CONSTANT

or

"this is " . constant("MY_CONSTANT");
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top