Using curly braces in php

Curly braces in string in PHP

I’ve also found it useful to access object attributes where the attribute names vary by some iterator. For example, I have used the pattern below for a set of time periods: hour, day, month.

$periods=array('hour', 'day', 'month'); foreach ($periods as $period) < $this->=1; > 

This same pattern can also be used to access class methods. Just build up the method name in the same manner, using strings and string variables.

You could easily argue to just use an array for the value storage by period. If this application were PHP only, I would agree. I use this pattern when the class attributes map to fields in a database table. While it is possible to store arrays in a database using serialization, it is inefficient, and pointless if the individual fields must be indexed. I often add an array of the field names, keyed by the iterator, for the best of both worlds.

class timevalues < // Database table values: public $value_hour; // maps to values.value_hour public $value_day; // maps to values.value_day public $value_month; // maps to values.value_month public $values=array(); public function __construct() < $this->value_hour=0; $this->value_day=0; $this->value_month=0; $this->values=array( 'hour'=>$this->value_hour, 'day'=>$this->value_day, 'month'=>$this->value_month, ); > > 

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

Читайте также:  Your Webpage Title Goes Here

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

 echo "This is < $great>"; // Works, outputs: This is fantastic echo "This is "; echo "This is $"; // Works echo "This square is width>00 centimeters broad."; // Works, quoted keys only work using the curly brace syntax echo "This works: "; // Works echo "This works: "; // 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: "; // Works. When using multi-dimensional arrays, always use braces around arrays // when inside of strings echo "This works: "; // Works. echo "This works: " . $arr['foo'][3]; echo "This works too: values[3]->name>"; echo "This is the value of the var named $name: >"; echo "This is the value of the var named by the return value of getName(): >"; echo "This is the value of the var named by the return value of \$object->getName(): getName()>>"; // Won't work, outputs: This is the return value of getName(): echo "This is the return value of getName(): "; ?> 

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

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

behaves exactly the same as this:

Читайте также:  Показать содержимое файла php

So the curly braces are unnecessary. But this:

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:

$number = 4; print "You have the th edition book"; //output: "You have the 4th edition book"; 

Without curly braces PHP would try to find a variable named $numberth , that doesn’t exist!

As for me, curly braces serve as a substitution for concatenation, they are quicker to type and code looks cleaner. Remember to use double quotes (» «) as their content is parsed by PHP, because in single quotes (‘ ‘) you’ll get the literal name of variable provided:

rty"; // qwe12345rty, using braces echo "qwe" . $a . "rty"; // qwe12345rty, concatenation used // Does not work: echo 'qwerty'; // qwerty, single quotes are not parsed echo "qwe$arty"; // qwe, because $a became $arty, which is undefined ?> 

Источник

PHP RFC: Deprecate curly brace syntax for accessing array elements and string offsets

PHP allows both square brackets and curly braces to be used interchangeably for accessing array elements and string offsets. For example:

$array = [1, 2]; echo $array[1]; // prints 2 echo $array{1}; // also prints 2 $string = "foo"; echo $string[0]; // prints "f" echo $string{0}; // also prints "f"

However, supporting both of these syntaxes can be confusing. Are there circumstances where one syntax behaves differently than the other? Is there a difference in performance between them? Is there some difference in scoping, since curly braces are the standard way to separate scope? What’s the purpose of the curly brace syntax?

Apart from two short notes in the PHP Manual, the curly brace syntax is virtually undocumented. Furthermore, it has reduced functionality compared to the normal bracket syntax. For example, it cannot be used for pushing an element into an array:

$array[] = 3; echo $array[2]; // prints 3 $array{} = 3; // Parse error: syntax error, unexpected '>'

Nor can it be used to create an array:

$array = [1, 2]; // works $array = {1, 2}; // Parse error: syntax error, unexpected '

It can’t be used for list assignment, either:

[$one, $two] = $array; // works {$one, $two} = $array; // Parse error: syntax error, unexpected ','

Proposal

Deprecate curly brace syntax for accessing array elements and string offsets.

Deprecated: Array and string offset access syntax with curly braces is deprecated in test.php line 3 int(2)

Discussion

Wasn’t the curly brace syntax deprecated once before?

According to an internals discussion from June 2008 (see references below), the curly brace syntax was deprecated in PHP 5.1 RC5, but the deprecation warning was removed before the final release. In August 2006, the documentation for $str read “deprecated as of PHP 6”, but again the deprecation never made it into a production release.

Is the curly brace syntax valuable for differentiating string and array offset access?

It has been suggested that the duplicate syntax is useful for differentiating string and array offset access. The problem with this is that no distinction is enforced by the language. Both syntaxes can be used for both arrays and strings, so while one codebase might always use $str[0] for strings and $arr for arrays, another codebase might use the opposite convention, which leads to more confusion rather than less.

To make sure that code is indexing a string and not an array, a type check should be used instead of relying on syntax that can be used for both strings and arrays (and thus doesn’t tell you anything about the underlying type).

How frequently is the curly brace syntax used?

Nikita Popov checked the top 2k Composer packages, and found ~2.2k individual uses of the curly brace array syntax. Compared to the 888.3k total array accesses in the data set, usage of the alternative syntax is about 0.25%. However, even this number is inflated somewhat due to duplicate packages (for example, there are two packages that mirror the WordPress Core repository, each with 182 usages). 92% of usages in the top 2k packages are in just 25 unique projects.

Will it be too much work for people to migrate code away from the curly brace syntax?

A migration script has been implemented alongside the deprecation patch: https://gist.github.com/theodorejb/763b83a43522b0fc1755a537663b1863

Backward Incompatible Changes

A deprecation warning will be output when using the curly brace syntax to access array or string offsets.

Vote

Started 3 July 2019. Ends 17th July 2019

Future Scope

Remove the feature entirely (replacing the deprecation warning with a compiler error) in PHP 8 or another future release.

Источник

PHP Curly Braces: How and When to Use it?

New here? Like SchoolsOfWeb on Facebook to stay up to date with new posts.

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 —

Curly braces example

Now, see an example of curly braces below-

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-

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-

s to defining variable in a string."; ?>

Output:
Two ways to defining variable in a string.

Источник

PHP RFC: Deprecate curly brace syntax for accessing array elements and string offsets

PHP allows both square brackets and curly braces to be used interchangeably for accessing array elements and string offsets. For example:

$array = [1, 2]; echo $array[1]; // prints 2 echo $array{1}; // also prints 2 $string = "foo"; echo $string[0]; // prints "f" echo $string{0}; // also prints "f"

However, supporting both of these syntaxes can be confusing. Are there circumstances where one syntax behaves differently than the other? Is there a difference in performance between them? Is there some difference in scoping, since curly braces are the standard way to separate scope? What’s the purpose of the curly brace syntax?

Apart from two short notes in the PHP Manual, the curly brace syntax is virtually undocumented. Furthermore, it has reduced functionality compared to the normal bracket syntax. For example, it cannot be used for pushing an element into an array:

$array[] = 3; echo $array[2]; // prints 3 $array{} = 3; // Parse error: syntax error, unexpected '>'

Nor can it be used to create an array:

$array = [1, 2]; // works $array = {1, 2}; // Parse error: syntax error, unexpected '

It can’t be used for list assignment, either:

[$one, $two] = $array; // works {$one, $two} = $array; // Parse error: syntax error, unexpected ','

Proposal

Deprecate curly brace syntax for accessing array elements and string offsets.

Deprecated: Array and string offset access syntax with curly braces is deprecated in test.php line 3 int(2)

Discussion

Wasn’t the curly brace syntax deprecated once before?

According to an internals discussion from June 2008 (see references below), the curly brace syntax was deprecated in PHP 5.1 RC5, but the deprecation warning was removed before the final release. In August 2006, the documentation for $str read “deprecated as of PHP 6”, but again the deprecation never made it into a production release.

Is the curly brace syntax valuable for differentiating string and array offset access?

It has been suggested that the duplicate syntax is useful for differentiating string and array offset access. The problem with this is that no distinction is enforced by the language. Both syntaxes can be used for both arrays and strings, so while one codebase might always use $str[0] for strings and $arr for arrays, another codebase might use the opposite convention, which leads to more confusion rather than less.

To make sure that code is indexing a string and not an array, a type check should be used instead of relying on syntax that can be used for both strings and arrays (and thus doesn’t tell you anything about the underlying type).

How frequently is the curly brace syntax used?

Nikita Popov checked the top 2k Composer packages, and found ~2.2k individual uses of the curly brace array syntax. Compared to the 888.3k total array accesses in the data set, usage of the alternative syntax is about 0.25%. However, even this number is inflated somewhat due to duplicate packages (for example, there are two packages that mirror the WordPress Core repository, each with 182 usages). 92% of usages in the top 2k packages are in just 25 unique projects.

Will it be too much work for people to migrate code away from the curly brace syntax?

A migration script has been implemented alongside the deprecation patch: https://gist.github.com/theodorejb/763b83a43522b0fc1755a537663b1863

Backward Incompatible Changes

A deprecation warning will be output when using the curly brace syntax to access array or string offsets.

Vote

Started 3 July 2019. Ends 17th July 2019

Future Scope

Remove the feature entirely (replacing the deprecation warning with a compiler error) in PHP 8 or another future release.

Источник

Оцените статью