PHP variable variables in {} symbols - php

I get the basics of variable variables, but I saw a syntax just know, which bogles my mind a bit.
$this->{$toShow}();
I don't really see what those {} symbols are doing there. Do they have any special meaning?

PHP's variable parser isn't greedy. The {} are used to indicate what should be considered part of a variable reference and what isn't. Consider this:
$arr = array();
$arr[3] = array();
$arr[3][4] = 'Hi there';
echo "$arr[3][4]";
Notice the double quotes. You'd expect this to output Hi there, but you actually end up seeing Array[4]. This is due to the non-greediness of the parser. It will check for only ONE level of array indexing while interpolating variables into the string, so what it really saw was this:
echo $arr[3], "[4]";
But, doing
echo "{$arr[3][4]}";
forces PHP to treat everything inside the braces as a variable reference, and you end up with the expected Hi there.

They tell the parser, where a variable name starts and ends. In this particular case it might not be needed, but consider this example:
$this->$toShow[0]
What should the parser do? Is $toShow an array or $this->$toShow ? In this case, the variable is resolved first and the array index is applied to the resulting property.
So if you actually want to access $toShow[0], you have to write:
$this->{$toShow[0]}

These curly braces can be used to use expressions to specify the variable identifier instead of just a variable’s value:
$var = 'foo';
echo ${$var.'bar'}; // echoes the value of $foobar
echo $$var.'bar'; // echoes the value of $foo concatenated with "bar"

$this->{$toShow}();
Break it down as below:
First this is a object oriented programming style as you got to see $this and ->. Second, {$toShow}() is a method(function) as you can see the () brackets.
So now {$toShow}() should somehow be parsed to a name like 'compute()'. And, $toShow is just a variable which might hold a possible function name. But the question remains, why is {} used around.
The reason is {} brackets substitues the value in the place. To clarify,
$toShow="compute";
so,
{$toShow}(); //is equivalent to compute();
but this is not true:
$toShow(); //this is wrong as a variablename is not a legal function name

Related

When to wrap curly braces around a variable

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} doesn't work everything. When should we use {$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/
A couple of years late but may I add:
You can even use variable in curly braces to access methods of an Object from a Class dynamically.
Example:
$username_method = 'username';
$realname_method = 'realname';
$username = $user->{$username_method}; // $user->username;
$name = $user->{$realname_method}; // $user->realname
Not a good example but to demonstrate the functionality.
Another Example as per #kapreski's request in the comments.
/**Lets say you need to get some details about the user and store in an
array for whatever reason.
Make an array of what properties you need to insert.
The following would make sense if the properties was massive. Assume it is
**/
$user = $this->getUser(); //Fetching User object
$userProp = array('uid','username','realname','address','email','age');
$userDetails = array();
foreach($userProp as $key => $property) {
$userDetails[] = $user->{$property};
}
print_r($userDetails);
Once the loop completes you will see records fetched from user object in your $userDetails array.
Tested on php 5.6
As far as I know, you can use for variable $x
echo "this is my variable value : $x dollars";
… but if you don't have any spaces between the variable and the text around it, you should use {}. For example:
echo "this is my variable:{$x}dollars";
because if you wrote it $xdollars it will interpret it as another variable.

What does { } do within a string?

$name = "jason";
$p = "hello-{hello2}-$name-{$name}";
echo $p;
output :
hello-{hello2}-jason-jason
Came across some examples of prepared statements and noticed this. If its encompassing a variable, it removes them, otherwise it keeps them. Why is this behavior necessary when
echo "$name";
gets you the same result as
echo "{$name}";
or is it just readability?
It's used as a delimiter for variables in strings. This is necessary in some cases, as PHP's string parser isn't Greedy aand will mis-interpret many common structs.
e.g.
$foo = array();
$foo['bar'] = array();
$foo['bar']['baz'] = 'qux';
echo "Hello $foo[bar][baz]";
will actually print
Hello Array[baz]
Because it's parsed as
echo "Hello ", $foo['bar'], "[baz]";
^ ^ ^
string array string
Using {} forces PHP to consider the array reference as single entity:
echo "Hello, {$foo['bar']['baz']}"; // prints "Hello, qux"
It also helps differentiate ambiguous stuff
$foo = 'bar';
echo "$foos" // undefined variable 'foos'
echo "{$foo}s" // variable containing 'bar' + string 's'
It's something called "complex syntax"
From php.net you can go to Complex (curly) syntax section and see many examples.
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 {$.
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.
It does not necessarily generate the same output:
$name = 'foo';
$names = 'bar';
echo "Output1: $names";
echo "Output2: {$name}s";
Output
Output1: bar
Output2: foos
Also you can access complex structures via the curly syntax like {$foo->bar}.
This syntax is useful when you want to display variable following some string and you don't want any space between them.
Compare the following:
<?php
$name='John';
echo "My name is $nameathan. I'm twenty years old<br />";
echo "My name is {$name}athan. I'm twenty years old<br />";
It will give you result:
Notice: Undefined variable: nameathan in ... on line 5
My name is . I'm twenty years old
My name is Johnathan. I'm twenty years old
For first echo it will generate notice and won't work as expected because PHP doesn't know that you want to use variable $name in the string and not $nameathan. Using curly braces in second case solves the issue.
Of course you can concatenate string this way:
echo "My name is $name"."athan. I'm twenty years old<br />";
and it also solves the issue but if you have many such variables in string it will be much more convenient to use curly braces.

would it make a difference if I omit single quotes in $_variable['variable']? [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Accessing arrays whitout quoting the key
I noticed there's a subtle difference... if I were to code this:
echo "Welcome, $_SESSION['username'], you are logged in.";
It will fail at parsing. However if I code like this:
echo "Welcome, $_SESSION[username], you are logged in.";
It works as expected which makes me wonder if single quotes are really necessary? I cannot find anything in PHP documentation showing that effect.
In PHP, a global constant that isn't defined becomes a string.
Don't rely on this; always quote your array keys.
However, interpolated into a string, it is fine, as it is already a string.
Konforce makes a good point in the comments about using braces in string interpolation.
If you omit them, don't quote the key.
If you use them, you must quote the key, otherwise the constant will be looked up.
This way is wrong but works$_SESSION[username] and take more time to parse the value of that associative index.
That effect PHP performance
Always use quotes around a string
literal array index. For example,
$foo['bar'] is correct, while
$foo[bar] is not. This is wrong, but
it works. The reason is that this code
has an undefined constant (bar) rather
than a string ('bar' - notice the
quotes).PHP may in future define constants which, unfortunately for such code, have the same name. It works because PHP automatically converts a bare string (an unquoted string which does not correspond to any known symbol) into a string which contains the bare string. For instance, if there is no defined constant named bar, then PHP will substitute in the string 'bar' and use that.
you should use quotes while accessing values.
Please check this document
in section Array do's and don'ts
<?php
// Show all errors
error_reporting(E_ALL);
$arr = array('fruit' => 'apple', 'veggie' => 'carrot');
// Correct
print $arr['fruit']; // apple
print $arr['veggie']; // carrot
// Incorrect. This works but also throws a PHP error of level E_NOTICE because
// of an undefined constant named fruit
//
// Notice: Use of undefined constant fruit - assumed 'fruit' in...
print $arr[fruit]; // apple
// This defines a constant to demonstrate what's going on. The value 'veggie'
// is assigned to a constant named fruit.
define('fruit', 'veggie');
// Notice the difference now
print $arr['fruit']; // apple
print $arr[fruit]; // carrot
// The following is okay, as it's inside a string. Constants are not looked for
// within strings, so no E_NOTICE occurs here
print "Hello $arr[fruit]"; // Hello apple
// With one exception: braces surrounding arrays within strings allows constants
// to be interpreted
print "Hello {$arr[fruit]}"; // Hello carrot
print "Hello {$arr['fruit']}"; // Hello apple
// This will not work, and will result in a parse error, such as:
// Parse error: parse error, expecting T_STRING' or T_VARIABLE' or T_NUM_STRING'
// This of course applies to using superglobals in strings as well
print "Hello $arr['fruit']";
print "Hello $_GET['foo']";
// Concatenation is another option
print "Hello " . $arr['fruit']; // Hello apple
?>
Inside a string you have to omit the single quotes or wrap the whole variable in {} ("...{$array['key']}..." or ...$array[key]...). However, wrapping it is highly recommended to prevent issues when having something like "...$foobar..." where you actually wanted "...{$foo}bar..." (i.e. the var $foo followed by bar).
But you might not want to use in-string vars at all but properly end the string: '...' . $var . '...'
It's called bare strings as mentioned, strangly enough, in the array documentation. If no constant is found matching the bare string - It's, for historical reasons, assumbed to be a string literal. This syntax is however ridden with a lot of syntactic problems that I won't go into, also readability is a problem here. The reader questions himself - Is this a constant or a string?
Modern PHP versions emit a warning for this syntax, as to help fix this problem by using singly quoted strings ('username').
yes.
If you pass an argument for an array without any quotes, php will first try to interpret the argument as a constant and if it isn't defined, it will act as expected.Even though it can give the same result, it is significantly slower that the quoted argument.
Here's an example of when this might not work :
define("a_constant","a value");
$a = array("a_constant"=>"the right value");
echo $a[a_constant];
The a_constant variable has the value "a value", so $a[a_constant] gets translated to $a["a value"], a key which does not exist in the array $a.

Help understanding how the brackets are used... Rookie Question

I understand what the following line does but i don't understand how the brackets are used? I have always used brackets in an if, while and other statements but i have never used them in this fashion.
Are there rules to using them this way, should i not use them in this way? Any help would be appreciated... Thanks
${$key} = $temp;
In that specific case, there is effectively no difference between using brackets and not.
So your code is equivalent to the following:
$$key = $temp;
The brackets are typically used to force PHP to interpolate variables in strings, which isn't necessary in this case.
Using the brackets is very helpful for reducing ambiguity in a statement using array indices:
${$array[0]} = $temp;
As opposed to
$$array[0] = $temp;
The parser will think that you meant ($$array)[0], not $($array[0])
Have a look at:
Variable variables
Today I learned about PHP variable variables; "variable variable takes the value of a variable and treats that as the name of a variable". Also, variable
It seems to be using variable variables.
Otherwise, braces like that are usually used for variable interpolation in strings, where the variable is an object property or array member.
In the example above, they are not necessary. It also seems you can subscript an array with variable variables, with no issues.

Constants inside quotes are not printed?

This prints apple:
define("CONSTANT","apple");
echo CONSTANT;
But this doesn't:
echo "This is a constant: CONSTANT";
Why?
Because "constants inside quotes are not printed". The correct form is:
echo "This is a constant: " . CONSTANT;
The dot is the concatenation operator.
define('QUICK', 'slow');
define('FOX', 'fox');
$K = 'strval';
echo "The {$K(QUICK)} brown {$K(FOX)} jumps over the lazy dog's {$K(BACK)}.";
If you want to include references to variables inside of strings you need to use special syntax. This feature is called string interpolation and is included in most scripting languages.
This page describes the feature in PHP. It appears that constants are not replaced during string interpolation in PHP, so the only way to get the behavior you want is to use the concatenation that Artefacto suggested.
In fact, I just found another post saying as much:
AFAIK, with static variables, one has
the same 'problem' as with constants:
no interpolation possible, just use
temporary variables or concatenation.
Concatenation has been suggested as the only solution here, but that doesn't work when using syntax like:
define("MY_CONSTANT", "some information");
$html = <<< EOS
<p>Some html, **put MY_CONSTANT here**</p>
EOS;
Of course, the above just puts the text 'MY_CONSTANT' in $html.
Other options include:
define a temporary variable to hold the constant:
$myConst = MY_CONSTANT;
$html = <<< EOS
<p>Some html, {$myConst} </p>
EOS;
if there are many constants, you can get an array of them all and use that:
$constants = get_defined_constants();
$html = <<< EOS
<p>Some html, {$constants["MY_CONSTANT"]} </p>
EOS;
Of course, in such a trivially short example, there's no reason to use the <<< operator, but with a longer block of output the above two may be much clearer and easier to maintain than a bunch of string concatenation!
The question was already answered, but I'd like to provide a more generic insight on this.
In double quotes, PHP recognizes anything starting with a $ as a variable to be interpolated. Further more, it considers array and object access ([] and ->) but only up to a single level. E.g. "$foo->bar" interpolates $foo->bar and $foo->bar->baz does the same thing and treats ->baz as a string literally. Also, the quotes in [] must be ommited for string keys. E.g. "$foo[bar]" interpolates $foo['bar'] while "$foo['bar']" is a syntax error. AFAIK, that's it. To get more functionality, you need the "{$...}" syntax.
The $ here is actually a part of the syntax and it doesn't work without it. E.g. "{FOO}" will not interpolate a constant FOO, it's simply a syntax error. However, other than some strange syntactical restrictions, this construct is actually quite strong and may contain any valid PHP expression, as long as it starts with a $ and is an array access, object access, or a function call. (Maybe some other cases are permitted to. Please let me know, if anyone has a better understanding of this.) The most general solution to your problem would be to define something like the following function somewhere in your code base:
$id = function ($x) {
return $x;
}
It's simply the identity function - it returns whatever you give it. It must be defined as an anonymous function, so you can refer to it as $id with the $.
Now you can use this function to interpolate any PHP expression:
echo "{$id(CONSTANTS)}"
echo "{$id($some + $operators - $as . $well)}"
// etc...
Alternative for PHP versions < 5.3 where you can't use anonymous functoins:
class Util {
function id ($x) { return $x; }
}
$u = new Util;
echo "{$u->id(ANY + $expression . $here)}"
// or...
function id ($x) { return $x; };
$id = 'id';
echo "{$id(ANY + $expression . $here)}"
The native interpolation does not support constants. Still not up to PHP 8.2 (and maybe later on). An alternative to echo is to use printf() or sprintf() for getting the interpolation result as string.
const MY_CONSTANT = "foo";
printf("Hello %s bar!", MY_CONSTANT);

Categories