我不知道如何解释这一点,但简单来说,我看到人们{$variable}
在输出值时使用.我注意到{$variable}
一切都不起作用.我们应该何时使用{$variable}
?
Fak*_*ala 60
什么是PHP花括号:
您知道可以用四种不同的方式指定字符串.其中两种方法是 - 双引号("")和heredoc语法.您可以在这两种类型的字符串中定义变量,PHP解释器也会在字符串中解析或解释该变量.
现在,有两种方法可以在字符串中定义变量 - 简单语法是在字符串中定义变量的最常用方法,复杂语法使用花括号来定义变量.
卷曲括号语法:
使用带花括号的变量非常容易.只需用{和}包装变量,如:
{$variable_name}
注意:{和$之间一定不能有任何差距.否则,PHP解释器不会将$后面的字符串视为变量.
卷曲括号示例:
<?php
$lang = "PHP";
echo "You are learning to use curly braces in {$lang}.";
?>
Run Code Online (Sandbox Code Playgroud)
输出:
You are learning to use curly braces in PHP.
Run Code Online (Sandbox Code Playgroud)
何时使用花括号:
当您在字符串中定义变量时,如果使用简单的语法来定义变量,PHP可能会将变量与其他字符混淆,这会产生错误.请参阅以下示例:
<?php
$var = "way";
echo "Two $vars to defining variable in a string.";
?>
Run Code Online (Sandbox Code Playgroud)
输出:
Notice: Undefined variable: vars …
Run Code Online (Sandbox Code Playgroud)
在上面的例子中,PHP的解释器认为$ vars是一个变量,但变量是$ var.要将变量名和字符串中的其他字符分开,可以使用花括号.现在,使用花括号看上面的例子 -
<?php
$var = "way";
echo "Two {$var}s to define a variable in a string.";
?>
Run Code Online (Sandbox Code Playgroud)
输出:
Two ways to define a variable in a string.
Run Code Online (Sandbox Code Playgroud)
资料来源:http://schoolsofweb.com/php-curly-braces-how-and-when-to-use-it/
San*_*ung 12
迟了几年但我可以补充一下.
您甚至可以在花括号中使用变量来动态地从类中访问对象的方法.
例如
$usernamemethod = 'username';
$realnamemethod = 'realname';
$username = $user->{$usernamemethod}; // $user->username;
$name = $user->{$realnamemethod}; // $user->realname
Run Code Online (Sandbox Code Playgroud)
不是一个很好的例子,只是为了演示功能.
根据@ kapreski的评论中的另一个例子.
/**Lets say you need to get some details about the user and store in an
array for whatever reason.
Make an array of what properties you need to insert.
The following would make sense if the properties was massive. Assume it is
**/
$user = $this->getUser(); //Fetching User object
$userProp = array('uid','username','realname','address','email','age');
$userDetails = array();
foreach($userProp as $key => $property) {
$userDetails[] = $user->{$property};
}
print_r($userDetails);
Run Code Online (Sandbox Code Playgroud)
循环完成后,您将看到从$userDetails
数组中的用户对象获取的记录.
在PHP 5.6上测试过
归档时间: |
|
查看次数: |
20547 次 |
最近记录: |