我不知道如何解释这一点,但简单地说,我见过人们在输出值时使用{$variable}。我注意到{$variable}并不是万能的。我们什么时候应该使用{$variable}
发布于 2016-02-24 17:39:39
什么是PHP大括号:
您知道,字符串可以通过四种不同的方式指定。其中两种方式是-双引号(“”)和heredoc语法。您可以在这两种类型的字符串中定义一个变量,PHP解释器也会在字符串中解析或解释该变量。
现在,有两种方法可以在字符串中定义变量-简单语法和复杂语法。简单语法是在字符串中定义变量的最常用方法,复杂语法使用花括号定义变量。
大括号语法:
使用带大括号的变量非常容易。只需使用{ and }包装变量即可,如:
{$variable_name}
注意:{和$之间不能有任何间隙。否则,PHP解释器不会将$之后的字符串视为变量。
大括号示例:
<?php
$lang = "PHP";
echo "You are learning to use curly braces in {$lang}.";
?>输出:
You are learning to use curly braces in PHP.何时使用大括号:
在字符串中定义变量时,如果使用简单的语法定义变量,PHP可能会将变量与其他字符混淆,这将产生错误。如下例所示:
<?php
$var = "way";
echo "Two $vars to defining variable in a string.";
?>输出:
Notice: Undefined variable: vars …在上面的例子中,PHP的解释器认为$vars是一个变量,但这个变量是$var。要将变量名和字符串中的其他字符分开,可以使用大括号。现在,请看上面使用花括号的示例-
<?php
$var = "way";
echo "Two {$var}s to define a variable in a string.";
?>输出:
Two ways to define a variable in a string.来源:http://schoolsofweb.com/php-curly-braces-how-and-when-to-use-it/
发布于 2018-04-11 17:13:05
晚了几年,但请允许我补充一句:
您甚至可以在花括号中使用变量来动态访问来自类的对象的方法。
示例:
$username_method = 'username';
$realname_method = 'realname';
$username = $user->{$username_method}; // $user->username;
$name = $user->{$realname_method}; // $user->realname这不是一个很好的例子,但是为了演示它的功能。
另一个例子是根据@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);循环完成后,您将看到从$userDetails数组中的user对象获取的记录。
在php 5.6上测试
发布于 2019-06-21 05:20:53
据我所知,您可以使用for variable $x
echo "this is my variable value : $x dollars";…但是,如果变量和它周围的文本之间没有任何空格,则应该使用{}。例如:
echo "this is my variable:{$x}dollars";因为如果你写的是$xdollars,它会把它解释成另一个变量。
https://stackoverflow.com/questions/35598187
复制相似问题