开发者

PHP: variables in strings without concatenation

开发者 https://www.devze.com 2023-03-27 20:19 出处:网络
If I have a variable $var in this string: echo \"Hello, there are many $vars\"; Php looks for the variable $vars instead of $var.

If I have a variable $var in this string: echo "Hello, there are many $vars";

Php looks for the variable $vars instead of $var.

Without concatenation like: "Hello, there are many $var" . "s";

is there another way to do this, like some sort of escaping character开发者_运维问答?


In php you can escape variables like so

echo "Hello, ${var}'s head is big";

or like

echo "Hello, {$var}'s head is big";

Reference here under escape character section


You can use {} to escape your variable properly. Consider the following example:

echo "There are many ${var}s"; #Or...
echo "There are many {$var}s";

Working example


Alternatively you may want to look at sprintf: http://php.net/manual/en/function.sprintf.php

The sprintf function allows you to format any type of variable as a string in a specific notation.


Personally I always divide the variables from a string like this: echo 'Hello, there are many '.$var.'s';

Mostly because of readability, if you go through your code it's instantly clear where the variables are.

0

精彩评论

暂无评论...
验证码 换一张
取 消