字串插值

你還可以使用插值在字串中插入( 插入 )變數。插值僅使用雙引號字串和 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 的資訊