Home  >  Article  >  Backend Development  >  syntax - PHP 中 ${ } 是什么意思?

syntax - PHP 中 ${ } 是什么意思?

WBOY
WBOYOriginal
2016-06-06 20:39:201301browse

用 PHP 有一小段时间了,知道 $username 是代表一个变量,而且很多情况下都是这么写。
今天突然在一个地方看到 "${username}" 这样的写法,瞬间就不明白了。
这个${ }是用来做什么呢,这玩意儿在 google 里不知道该怎么搜,搜不出来呃。

回复内容:

用 PHP 有一小段时间了,知道 $username 是代表一个变量,而且很多情况下都是这么写。
今天突然在一个地方看到 "${username}" 这样的写法,瞬间就不明白了。
这个${ }是用来做什么呢,这玩意儿在 google 里不知道该怎么搜,搜不出来呃。

参考:http://php.net/manual/en/language.var...
为了解决一个模棱两可的问题,用在可能产生歧义的地方,明确告诉编译器如何解释代码。

// DaiJie 的代码中有一种以上的解释,php解释器不知道什么是对的。
$c = array('d'=>'e');
echo "{$c}['d']"; // Array['d']

$c = array('d'=>'e');
echo "${c['d']}"; // e
// null 的代码也有歧义
$var = "hello";
$var_ = "world";
echo "{$var}_ $var_"; //hello_ world

$var = "hello";
$var_ = "world";
echo "{$var_} $var_"; // world world

防止蹿变量的

<?php $var = "hello";
$var_ = "world";
echo "{$var}_ $var_";

变量名中的花括号的用途是提高优先级。

$title=1;
${"title_default_" . $title} = "selected";
echo $title_default_1;
//可变变量的 写法

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn