$ {}在PHP语法中是什么意思? [英] What does ${ } mean in PHP syntax?

查看:102
本文介绍了$ {}在PHP语法中是什么意思?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have used PHP for a long time, but I just saw something like,

${  } 

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

To be precise, I saw this in a PHP Mongo page:

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

那么,${ }是做什么的?在Google或PHP文档中很难搜索${}之类的字符.

So, what does ${ } do? It is quite hard to search with Google or in the PHP documentation for characters like $, { and }.

推荐答案

${ }(美元符号大括号)被称为

${ } (dollar sign curly bracket) is known as Complex (curly) syntax:

之所以称其为复杂",是因为其语法很复杂,而是因为它允许使用复杂的表达式.

This isn't called complex because the syntax is complex, but because it allows for the use of complex expressions.

带有 string 表示可以通过此语法包括在内.只需使用与 string 之外的表达式相同的方式编写表达式即可. a>,然后将其包装在{}中.由于无法逃避{,因此仅当$紧跟在{之后,才能识别此语法.使用{\$获取文字{$.一些例子可以使它更清楚:

Any scalar variable, array element or object property with a string representation can be included via this syntax. Simply write the expression the same way as it would appear outside the string, and then wrap it in { and }. Since { can not be escaped, this syntax will only be recognised when the $ immediately follows the {. Use {\$ to get a literal {$. Some examples to make it clear:

<?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()}";
?>

这篇关于$ {}在PHP语法中是什么意思?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆