何时将大括号括在变量周围

php
2022-08-30 10:59:49

我不知道如何解释这一点,但简单来说,我看到人们在输出值时使用。我注意到这并不奏效。我们什么时候应该使用?{$variable}{$variable}{$variable}


答案 1

什么是 PHP 大括号:

您知道可以通过四种不同的方式指定字符串。其中两种方式是 - 双引号(“”)和heredoc语法。您可以在这两种类型的字符串中定义一个变量,PHP解释器也将在字符串中解析或解释该变量。

现在,有两种方法可以在字符串中定义变量 - 简单语法(在字符串中定义变量的最常用方法)和使用大括号来定义变量的复杂语法。

大括号语法:

使用带有大括号的变量非常容易。只需用 { 和 } 包装变量,如下所示:

{$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/


答案 2

晚了几年,但我可以补充一点:

您甚至可以在大括号中使用变量来动态访问类中对象的方法。

例:

$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

在 php 5.6 上测试


推荐