quoting constants in php: “this is a MY_CONSTANT”

风格不统一 提交于 2019-12-17 16:32:31

问题


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!".


回答1:


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




回答2:


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.



回答3:


Concatenation is the way to go.

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

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



回答4:


no way, unless you write your own string parsing function




回答5:


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.




回答6:


Alternatively, do

"this is " . MY_CONSTANT

or

"this is " . constant("MY_CONSTANT");


来源:https://stackoverflow.com/questions/1563654/quoting-constants-in-php-this-is-a-my-constant

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!