何时将花括号括在变量中 [英] When to wrap curly braces around a variable

查看:122
本文介绍了何时将花括号括在变量中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不知道该怎么解释,但简单来说,我看到人们在输出值时使用{$variable}.我注意到{$variable}不能正常工作.什么时候应该使用{$variable}?

I don't know how to explain this but in simple terms I have seen people using {$variable} when outputting values. I have noticed that {$variable} doesn't work everything. When should we use {$variable}?

推荐答案

什么是PHP花括号:

您知道可以用四种不同的方式指定字符串.这些方式中的两种是–双引号(")和Heredoc语法.您可以在这两种类型的字符串中定义一个变量,PHP解释器也会在字符串中解析或解释该变量.

You know that a string can be specified in four different ways. Two of these ways are – double quote("") and heredoc syntax. You can define a variable in those 2 types of strings and PHP interpreter will parse or interpret that variable too, within the strings.

现在,有两种方法可以在字符串中定义变量:简单的语法(最常用的在字符串内部定义变量的方法)和复杂的语法(使用花括号定义变量).

Now, there are two ways you can define a variable in a string – simple syntax which is the most used method of defining variables inside a string and complex syntax which uses curly braces to define variables.

大括号语法:

使用带有花括号的变量非常容易.只需用{和}包裹变量即可,如:

To use a variable with curly braces is very easy. Just wrap the variable with { and } like:

{$variable_name}

注意:{和$之间不能有任何差距.否则,PHP解释器不会将$之后的字符串视为变量.

Note: There must not be any gap between { and $. Else, PHP interpreter won't consider the string after $ as a variable.

大括号示例:

<?php
$lang = "PHP";
echo "You are learning to use curly braces in {$lang}.";
?>

输出:

You are learning to use curly braces in PHP.

何时使用花括号:

在字符串中定义变量时,如果使用简单的语法定义变量,PHP可能会将变量与其他字符混合在一起,这会产生错误.请参见下面的示例:

When you are defining a variable inside a string, PHP might mix up the variable with other characters if using simple syntax to define a variable and this will produce an error. See the example below:

<?php
$var = "way";
echo "Two $vars to defining variable in a string.";
?>

输出:

Notice: Undefined variable: vars …

在上面的示例中,PHP的解释器将$ vars视为一个变量,但该变量为$ var.要分隔变量名和字符串中的其他字符,可以使用花括号.现在,使用花括号查看上面的示例-

In the above example, PHP's interpreter considers $vars a variable, but, the variable is $var. To separate a variable name and the other characters inside a string, you can use curly braces. Now, see the above example using curly braces-

<?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-以及何时使用它/

这篇关于何时将花括号括在变量中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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