Monday, 13 August 2018

PHP Curly Braces: How and When to Use it?

Problem:

You might have seen the usages of curly braces in different coding(ex. wordpress). You’re interested to learn it.
Solution:

In the following discussion, you’ll learn what a curly brace means in PHP and when to use it.
What is a 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 variable in those 2 types of string and PHP interpreter will parse or interpret that variable too.

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

To use a variable using 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 can’t consider the string after $ as a variable.
Curly braces example

Now, see an example of curly braces below
<?php
$lang = “PHP”;
echo “You are learning to use curly braces in {$lang}.”;
?>


Output:
You are learning to use curly braces in PHP.
When to use curly braces

When you’re defining a variable inside a string, it might mix up with other characters when you’re using simple syntax to define a variable and will produce error. See the example below-

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


Output:
Notice: Undefined variable: vars …

In the above example, PHP interpreter considers $vars a variable, but, the variable is $lang. 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 defining variable in a string.";
?>


Output:
Two ways to defining variable in a string.

0 comments:

Post a Comment