$ {}在PHP语法中意味着什么?

mur*_*lai 24 php syntax

我已经使用PHP很长一段时间了,但我刚看到类似的东西,

${  } 
Run Code Online (Sandbox Code Playgroud)

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

$m = new Mongo("mongodb://${username}:${password}@host");
Run Code Online (Sandbox Code Playgroud)

那么,该怎么${ }办?这是相当难与谷歌或像字符PHP文件中进行搜索$,{}.

cel*_*ker 31

${ }(美元符号大括号)称为复杂(卷曲)语法:

这不称为复杂,因为语法很复杂,但因为它允许使用复杂的表达式.

可以通过此语法包含具有字符串表示的任何标量变量,数组元素或对象属性.只需像在字符串外部一样编写表达式,然后将其包装在{和中}.由于{无法进行转义,因此只有在$紧随其后才能识别此语法{.使用{\$得到文字{$.一些例子说清楚:

<?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()}";
?>
Run Code Online (Sandbox Code Playgroud)


Cyc*_*one 7

它是一个嵌入式变量,因此它知道在哪里停止查找变量标识符的结尾.

${username}在字符串中表示字符串$username之外.这样,它不认为$u是变量标识符.

它在您提供的URL等情况下很有用,因为它在标识符后面不需要空格.

请参阅php.net部分.

  • 例如:`$ a ='blah'; echo"$ abc";`因为在$ $ ='blah'时未设置$ abc,所以不会回显任何内容; echo"$ {a} bc";`将回显'blahbc' (9认同)
  • 这里记录了"复杂(卷曲)语法":http://www.php.net/manual/en/language.types.string.php#language.types.string.parsing.complex - 顺便说一句,这些例子似乎更喜欢`{$ username}`而不是`$ {username}`虽然两者都适用于简单的情况. (3认同)
  • @PavelDubinin可读性.如果你将PHP优化到那个级别,为什么不只写C? (2认同)