PHP语法中的$ {}是什么意思?

我已经使用PHP很长一段时间,但我只是看到了一些像,

${ } 

准确地说,我在一个PHP Mongo页面中看到了这个:

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

那么, ${ }做什么的? 使用Google或PHP文档search${}这样的字符是非常困难的。

${ } (美元符号大括号)被称为复杂(curl)语法

这不称为复杂的,因为语法是复杂的,但是因为它允许使用复杂的expression式。

任何具有string表示的标量variables,数组元素或对象属性都可以通过此语法包含在内。 简单地写出expression式的方式与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()}"; ?> 

这是一个embedded式variables,所以它知道在哪里停止查找variables标识符的末尾。

一个string中的${username}意味着一个string之外的$username 。 这样,它不认为$u是variables标识符。

在你提供的URL的情况下,它是有用的,因为那么在标识符之后不需要空格。

看到关于它的php.net部分 。