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

时间:2011-04-06 19:06:56

标签: php syntax

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

${  } 

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

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

那么,${ }做了什么?使用Google或PHP文档搜索${}等字符非常困难。

3 个答案:

答案 0 :(得分:30)

${ }(美元符号大括号)称为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()}";
?>

答案 1 :(得分:7)

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

字符串中的

${username}表示字符串外的$username。这样,它不认为$u是变量标识符。

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

请参阅php.net section了解相关信息。

答案 2 :(得分:0)

我到处都在阅读有关在字符串中使用 ${var_name}{$var_name} 来分隔变量的信息,但我最近遇到了这个:

<?php
$zb8b5 = 419;
$GLOBALS['t91a5'] = Array();
global $t91a5;
$t91a5 = $GLOBALS;
${"\x47\x4c\x4fB\x41\x4c\x53"}['t112f6f9'] = "\x63\x5c\x76\x48\x36\x47\x43\x7b\x35\x7c\x27...";
.
.
.

我在修复被黑网站时发现了上述代码。

注意最后一行。事实证明,也可以使用 ${} 语法来声明具有奇数名称的变量。

所以你可以做(​​奇怪的)事情,比如:

<?php
${"my_var"} = 'asdf';
var_dump($my_var);
${"other_var"}['a_pos'] = 'my value';
var_dump($);
?>

输出:

string(4) "asdf"
array(1) {
  ["a_pos"]=>
  string(8) "my value"
}

当然,这确实是一种糟糕的做法,除非您像这些人想要的那样试图打乱您的代码。

我找不到任何关于 ${} 外部字符串使用的文档。