PHP Curly Brace Syntax For Member Variable

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

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/

Why do I need to wrap array variable with curly brackets in PHP sometimes

It's because you are echoing an array entry inside a double quoted string.

echo "hello $another_variable"; //works if $another_variable can be converted to string
echo "hello $arr['something']"; //error anyway
echo "hello {$arr['something']}"; //works

Basically, if you need to do something more complex than just using a simple $variable, you have to either use:

  • The curly brackets syntax: echo "my {$variable['foobar']}";
  • Concatenation: echo "my ".$variable['foobar'];

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.

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

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'].

PHP: What do the curly braces in $variable{0} do?

access the single byte with that index {0} => first char (in non-utf8 string)

you could simply test it with:

$var='hello';
echo $var{0};

What does brackets like {variable}(variable|array) statement means in php?

$this->_response($this->{$this->endpoint}($this->args));

Divide and conquer:

$this->_response()

Means calling the method _response() of the current object with the argument

$this->{$this->endpoint}($this->args)

The curly braces are explained here: http://php.net/manual/en/language.types.string.php

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 {$.

Therefore {$this->endpoint} evaluates to a string which was previously set as endpoint property of the current object.

$this->endpointproperty($this->args)

There must be a method endpoint property in the current object which accepts one argument. This Argument is also a property of this object:

$this->args

Is it wrong to use curly braces after the dollar sign inside strings

${...} is a syntax for another purpose. It is used to indirectly reference variable names. Without string interpolation, literal names in curly braces or brackets are written as string literals, thus enclosed in quotes. However, inside interpolation quotes are not used outside curly braces:

$bar = 'baz';

echo $bar , PHP_EOL;
echo ${'bar'} , PHP_EOL;

$arr = ['a' => 1, 'b' => ['x' => 'The X marks the point.']];
echo $arr['a'] , PHP_EOL;

// interpolation:
echo "$arr[a] / {$arr['a']}" , PHP_EOL;

Instead of literals you can use functions as well:

function foo(){return "bar";}

// Here we use the function return value as variable name.
// We need braces since without them the variable `$foo` would be expected
// to contain a callable

echo ${foo()} , PHP_EOL;

When interpolating, you need to enclose into curly braces only when the expression otherwise would be ambiguous:

echo "$arr[b][x]", PHP_EOL;       // "Array[x]"     
echo "{$arr['b']['x']}", PHP_EOL; // "The X marks the point."

Now we understand that ${...} is a simple interpolation "without braces" similar to "$arr[a]" since the curly braces are just for indirect varable name referencing. We can enclose this into curly braces nevertheless.

Interpolated function call forming the variable name:

echo "${foo()} / {${foo()}}", PHP_EOL;
// "baz / baz" since foo() returns 'bar' and $bar contains 'baz'.

Again, "${bar}" is equivalent to ${'bar'}, in curly braces: "{${'bar'}}".


As asked in comments,

there is another curly brace syntax to reference array keys.

$someIdentifier{'key'}

This is just an alternative syntax to PHP's common array syntax $array['key'].

In opposit to the latter, on indirect variable name references the curly braces follow immediately after the $ or the object member operator ->. To make it even more cryptic we can combine both:

$bar['baz'] = 'array item';
echo ${'ba' . 'r'}{'ba'.'z'};

which is equivalent to echo $bar['baz'];

Really weird in PHP's string interpolation: "${bar}" is valid and "${'bar'}" as well but not "$array['key']", "$array[key]" is valid instead, but both, "$array{key}" and "$array{'key'}", do not work at all.

Conclusion

It should be made a habit to use braced interpolation syntax all the time. Braced array key syntax should be avoided at all.

Always use:

"{$varname} {$array['key']} {${funcname().'_array'}['key']}"

See also PHP documentation:

  • Complex curly syntax

(to distinguish from)

  • Variable variables (also known as indirect variable name referencing)

  • Accessing array elements

    Both square brackets and curly braces can be used interchangeably for accessing array elements (e.g. $array[42] and $array{42} will both do the same thing in the example above).

Trouble using PHP complex (curly) syntax with static variables

What you want is simply not possible.

Functions, method calls, static class variables, and class constants
inside {$} work since PHP 5. However, the value accessed will be
interpreted as the name of a variable in the scope in which the string
is defined. Using single curly braces ({}) will not work for accessing
the return values of functions or methods or the values of class
constants or static class variables.

The easiest way around would be to just move the var access outside the string.

class asdf{
public static $variable = 'foo@';

public static function getValue() {
return asdf::$variable . 'bar.com';
}
}

doing this, you could even use the variable var syntax, if you need to

class asdf{
public static $variable = 'foo@';

public static function getValue($var = "variable") {
return asdf::$$var . 'bar.com';
}
}


Related Topics



Leave a reply



Submit