2011-04-06 63 views
19

我已經使用PHP很長一段時間,但我剛纔看到類似,

${ } 

準確地說,我看到這個在PHP蒙戈頁:

$m = new Mongo("mongodb://${username}:${password}@host"); 

那麼,是什麼${ }做?使用Google或PHP文檔搜索${}等字符非常困難。

+0

它的使用是一種毫無意義的,雖然在這裏,'「的mongodb:// $用戶名:密碼$ @ $主機」'會很好的工作。 – 2013-03-21 13:44:42

回答

27

${ }(美元符號波形括號)被稱爲Complex (curly) syntax

因爲語法是複雜這不叫複雜,但因爲它允許使用複雜的表達式。

任何具有string表示的標量變量,數組元素或對象屬性都可以通過此語法包含在內。簡單地寫出表達式與在string之外出現的方式相同,然後將其包裝在{}中。由於{不能轉義,因此只有當$緊跟在{之後時纔會識別此語法。使用{\$來得到一個文字{$。用一些例子可以更清晰:

<?php 
// Show all errors 
error_reporting(E_ALL); 

$great = 'fantastic'; 

// Won't work, outputs: This is { fantastic} 
echo "This is { $great}"; 

// Works, outputs: This is fantastic 
echo "This is {$great}"; 
echo "This is ${great}"; 

// Works 
echo "This square is {$square->width}00 centimeters broad."; 


// Works, quoted keys only work using the curly brace syntax 
echo "This works: {$arr['key']}"; 


// Works 
echo "This works: {$arr[4][3]}"; 

// This is wrong for the same reason as $foo[bar] is wrong outside a 
// string. In other words, it will still work, but only because PHP 
// first looks for a constant named foo; an error of level E_NOTICE 
// (undefined constant) will be thrown. 
echo "This is wrong: {$arr[foo][3]}"; 

// Works. When using multi-dimensional arrays, always use braces around 
// arrays when inside of strings 
echo "This works: {$arr['foo'][3]}"; 

// Works. 
echo "This works: " . $arr['foo'][3]; 

echo "This works too: {$obj->values[3]->name}"; 

echo "This is the value of the var named $name: {${$name}}"; 

echo "This is the value of the var named by the return value of " 
     . " getName(): {${getName()}}"; 

echo "This is the value of the var named by the return value of " 
     . "\$object->getName(): {${$object->getName()}}"; 

// Won't work, outputs: This is the return value of getName(): {getName()} 
echo "This is the return value of getName(): {getName()}"; 
?> 
7

這是一個嵌入式變量,因此它知道在哪裏停止查找變量標識符的末尾。

${username}中的字符串表示$username以外的字符串。這樣,它不認爲$u是變量標識符。

這對於您提供的URL等情況非常有用,因爲它在標識符之後不需要空格。

請參閱php.net section

+9

例如:'$ a ='blah'; echo「$ abc」;'將不會迴應,因爲$ abc沒有設置,而$ a ='blah';回聲「$ {a} bc」;'回聲'blahbc' – 2011-04-06 19:12:35

+2

「複雜(捲曲)語法」記錄在這裏:http://www.php.net/manual/en/language.types.string.php#language .types.string.parsing.complex - btw,示例似乎更喜歡'{$ username}'在'$ {username}'上,儘管兩者都適用於簡單情況。 – 2011-04-06 19:13:17

+0

+1鮑勃,很好的例子 – Cyclone 2011-04-06 19:19:48