Curly Braces Notation in PHP

Curly Braces Notation in PHP

Curly braces are used to denote string or variable interpolation in PHP. It allows you to create 'variable functions', which can allow you to call a function without explicitly knowing what it actually is.

Using this, you can create a property on an object almost like you would an array:

$property_name = 'foo';
$object->{$property_name} = 'bar';
// same as $object->foo = 'bar';

Or you can call one of a set of methods, if you have some sort of REST API class:

$allowed_methods = ('get', 'post', 'put', 'delete');
$method = strtolower($_SERVER['REQUEST_METHOD']); // eg, 'POST'

if (in_array($method, $allowed_methods)) {
return $this->{$method}();
// return $this->post();
}

It's also used in strings to more easily identify interpolation, if you want to:

$hello = 'Hello';
$result = "{$hello} world";

Of course these are simplifications. The purpose of your example code is to run one of a number of functions depending on the value of $result['code'].

Curly braces in string in PHP

This is the complex (curly) syntax for string interpolation. From the manual:

Complex (curly) syntax


This isn't called complex because the syntax is complex, but because
it allows for the use of complex expressions.

Any scalar variable, array element or object property with a string
representation can be included via this syntax. Simply write the
expression the same way as it would appear outside the string, and
then wrap it in { and }. Since { can not be escaped, this syntax
will only be recognised when the $ immediately follows the {. Use
{\$ to get a literal {$. Some examples to make it clear:

<?php
// Show all errors
error_reporting(E_ALL);

$great = 'fantastic';

// Won't work, outputs: This is { fantastic}
echo "This is { $great}";

// Works, outputs: This is fantastic
echo "This is {$great}";
echo "This is ${great}";

// Works
echo "This square is {$square->width}00 centimeters broad.";

// Works, quoted keys only work using the curly brace syntax
echo "This works: {$arr['key']}";

// Works
echo "This works: {$arr[4][3]}";

// This is wrong for the same reason as $foo[bar] is wrong outside a string.
// In other words, it will still work, but only because PHP first looks for a
// constant named foo; an error of level E_NOTICE (undefined constant) will be
// thrown.
echo "This is wrong: {$arr[foo][3]}";

// Works. When using multi-dimensional arrays, always use braces around arrays
// when inside of strings
echo "This works: {$arr['foo'][3]}";

// Works.
echo "This works: " . $arr['foo'][3];

echo "This works too: {$obj->values[3]->name}";

echo "This is the value of the var named $name: {${$name}}";

echo "This is the value of the var named by the return value of getName(): {${getName()}}";

echo "This is the value of the var named by the return value of \$object->getName(): {${$object->getName()}}";

// Won't work, outputs: This is the return value of getName(): {getName()}
echo "This is the return value of getName(): {getName()}";
?>

Often, this syntax is unnecessary. For example, this:

$a = 'abcd';
$out = "$a $a"; // "abcd abcd";

behaves exactly the same as this:

$out = "{$a} {$a}"; // same

So the curly braces are unnecessary. But this:

$out = "$aefgh";

will, depending on your error level, either not work or produce an error because there's no variable named $aefgh, so you need to do:

$out = "${a}efgh"; // or
$out = "{$a}efgh";

When to wrap curly braces around a variable

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:

<?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 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.";
?>

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-

<?php
$var = "way";
echo "Two {$var}s to define a variable in a string.";
?>

Output:

Two ways to define a variable in a string.

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

What is the use of Curly Braces in PHP mysql?

TL;DR: NO, IT DOES NOT PREVENT SQL INJECTION

The curly braces are a way to inject variable's content into the string. Reference: https://www.php.net/manual/en/language.types.string.php#language.types.string.syntax.double

So this two commands do exactly the same thing:

query("SELECT * FROM users WHERE email = $email AND password = $password");
query("SELECT * FROM users WHERE email = {$email} AND password = {$password}");

If it's the same, then why bother with curly braces? Because it's a way to inject an object's property/data member into string:

query("SELECT * FROM users WHERE email = {$user->email} AND password = {$user->password}");

By reading the filename retrieve.php and retrieve_safely.php, there's a difference that there's a quote around the variable in _safely file.

So, unless there's a kind of input sanitization before the code in retrieve_safely.php, that file is no more safe than retrieve.php

PHP curly brace syntax for member variable

Curly braces are used to explicitly specify the end of a variable name. For example:

echo "This square is {$square->width}00 centimeters broad."; 

So, your case is really a combination of two special cases. You're allowed to access class variables using curly braces and like so:

$class->{'variable_name'} // Same as $class->variable_name
$class->{'variable' . '_name'} // Dynamic values are also allowed

And in your case, you're just surrounding them with the curly brace syntax.

See the PHP manual, "complex (curly) syntax."

PHP arrays -- square brackets vs curly braces ($array[$i] vs $array{$i})

"Square bracket notation" for array elements would be more unified and acceptable.
"Curly bracket notation" will work in expressions but not in variable interpolation when dealing with accessing of an array element.
Consider the following example:

$myArray = [1,2];
$index = 1;

echo "value at index $index is $myArray[$index]"; // outputs "value at index 1 is 2"

echo "value at index $index is $myArray{$index}"; // will throw "Notice: Array to string conversion"

var_dump($myArray{$index}); // outputs "int(2)"

What does ${ } mean in PHP syntax?

${ } (dollar sign curly bracket) is known as Simple syntax.

It provides a way to embed a variable, an array value, or an object
property in a string with a minimum of effort.

If a dollar sign ($) is encountered, the parser will greedily take as
many tokens as possible to form a valid variable name. Enclose the
variable name in curly braces to explicitly specify the end of the
name.

<?php
$juice = "apple";

echo "He drank some $juice juice.".PHP_EOL;
// Invalid. "s" is a valid character for a variable name, but the variable is $juice.
echo "He drank some juice made of $juices.";
// Valid. Explicitly specify the end of the variable name by enclosing it in braces:
echo "He drank some juice made of ${juice}s.";
?>

The above example will output:

He drank some apple juice.
He drank some juice made of .
He drank some juice made of apples.

What is the current state of curly-brace-substring notation in PHP?

There is a small note in the string documentation saying:

Note: Strings may also be accessed using braces, as in $str{42}, for the same purpose.

So, it seems to be officially supported and not go away anytime soon.

PHP curly brace syntax for calling methods using string

It's part of variable functions. When using variable variables or variable functions, you can replace the variable with any expression that returns a string by wrapping on braces. So you can do:

$var = 'SayHi';
$player->$var();

or you can do it in one step with:

$player->{'SayHi'}();

The syntax with braces is shown in the documentation of variable variables. The example there is for a variable class property, but the same syntax is used for class methods.



Related Topics



Leave a reply



Submit