PHP: variables in strings without concatenation
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";
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.
精彩评论