字符串插值

你还可以使用插值在字符串中插入( 插入 )变量。插值仅使用双引号字符串和 heredoc 语法。

$name = 'Joel';

// $name will be replaced with `Joel`
echo "<p>Hello $name, Nice to see you.</p>";
#                ↕
#>   "<p>Hello Joel, Nice to see you.</p>"

// Single Quotes: outputs $name as the raw text (without interpreting it)
echo 'Hello $name, Nice to see you.'; # Careful with this notation
#> "Hello $name, Nice to see you."

复合物(花)语法 格式提供了需要你花括号内 {} 包装你的变量的另一种选择。当在文本内容中嵌入变量并帮助防止文本内容和变量之间可能存在歧义时,这可能很有用。

$name = 'Joel';

// Example using the curly brace syntax for the variable $name
echo "<p>We need more {$name}s to help us!</p>";
#> "<p>We need more Joels to help us!</p>"

// This line will throw an error (as `$names` is not defined)
echo "<p>We need more $names to help us!</p>";
#> "Notice: Undefined variable: names"

{} 语法仅将以 $ 开头的变量插入到字符串中。{} 语法不会评估任意 PHP 表达式。

// Example tying to interpolate a PHP expression
echo "1 + 2 = {1 + 2}";
#> "1 + 2 = {1 + 2}"

// Example using a constant
define("HELLO_WORLD", "Hello World!!");
echo "My constant is {HELLO_WORLD}";
#> "My constant is {HELLO_WORLD}"

// Example using a function
function say_hello() {
    return "Hello!";
};
echo "I say: {say_hello()}";
#> "I say: {say_hello()}"

但是,{} 语法会评估对变量,数组元素或属性的任何数组访问,属性访问和函数/方法调用:

// Example accessing a value from an array — multidimensional access is allowed
$companions = [0 => ['name' => 'Amy Pond'], 1 => ['name' => 'Dave Random']];
echo "The best companion is: {$companions[0]['name']}";
#> "The best companion is: Amy Pond"

// Example of calling a method on an instantiated object
class Person {
  function say_hello() {
    return "Hello!";
  }
}

$max = new Person();

echo "Max says: {$max->say_hello()}";
#> "Max says: Hello!"

// Example of invoking a Closure — the parameter list allows for custom expressions
$greet = function($num) {
    return "A $num greetings!";
};
echo "From us all: {$greet(10 ** 3)}";
#> "From us all: A 1000 greetings!"

请注意,如上例所示,美元 $ 符号可以出现在大括号 { 之后,或者像 Perl 或 Shell Script 一样,可以出现在它之前:

$name = 'Joel';

// Example using the curly brace syntax with dollar sign before the opening curly brace
echo "<p>We need more ${name}s to help us!</p>";
#> "<p>We need more Joels to help us!</p>"

Complex (curly) syntax 并不是这样称呼的,因为它很复杂,而是因为它允许使用复杂表达式了解更多关于 Complex (curly) syntax 的信息