When to wrap curly braces around a variable

前端 未结 3 1511
隐瞒了意图╮
隐瞒了意图╮ 2020-12-03 00:51

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}

3条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-03 01:19

    What are PHP curly braces:

    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.

    Curly braces syntax:

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

    {$variable_name}

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

    Curly braces example:

    
    

    Output:

    You are learning to use curly braces in PHP.
    

    When to use curly braces:

    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:

    
    

    Output:

    Notice: Undefined variable: vars …
    

    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-

    
    

    Output:

    Two ways to define a variable in a string.
    

    Source: http://schoolsofweb.com/php-curly-braces-how-and-when-to-use-it/

提交回复
热议问题