PHP dynamic name for object property - php

Instead of using
$object->my_property
I want to do something like this
$object->"my_".$variable

Use curly brackets like so:
$object->{'my_' . $variable}

How about this:
$object->{"my_$variable"};
I suppose this section of PHP documentation might be helpful. In short, one can write any arbitrary expression within curly braces; its result (a string) become a name of property to be addressed. For example:
$x = new StdClass();
$x->s1 = 'def';
echo $x->{'s' . print("abc\n")};
// prints
// abc
// def
... yet usually is far more readable to store the result of this expression into a temporary variable (which, btw, can be given a meaningful name). Like this:
$x = new StdClass();
$x->s1 = 'def';
$someWeirdPropertyName = 's' . print("abc\n"); // becomes 's1'.
echo $x->$someWeirdPropertyName;
As you see, this approach makes curly braces not necessary AND gives a reader at least some description of what composes the property name. )
P.S. print is used just to illustrate the potential complexity of variable name expression; while this kind of code is commonly used in certification tests, it's a big 'no-no' to use such things in production. )

Related

Looping through an object with incremental property names using PHP [duplicate]

Instead of using
$object->my_property
I want to do something like this
$object->"my_".$variable
Use curly brackets like so:
$object->{'my_' . $variable}
How about this:
$object->{"my_$variable"};
I suppose this section of PHP documentation might be helpful. In short, one can write any arbitrary expression within curly braces; its result (a string) become a name of property to be addressed. For example:
$x = new StdClass();
$x->s1 = 'def';
echo $x->{'s' . print("abc\n")};
// prints
// abc
// def
... yet usually is far more readable to store the result of this expression into a temporary variable (which, btw, can be given a meaningful name). Like this:
$x = new StdClass();
$x->s1 = 'def';
$someWeirdPropertyName = 's' . print("abc\n"); // becomes 's1'.
echo $x->$someWeirdPropertyName;
As you see, this approach makes curly braces not necessary AND gives a reader at least some description of what composes the property name. )
P.S. print is used just to illustrate the potential complexity of variable name expression; while this kind of code is commonly used in certification tests, it's a big 'no-no' to use such things in production. )

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 PHP operator ->{...} mean?

I recently saw this line in a PHP piece of code:
$dbObject = json_decode($jsonString);
$dbObject->{'mysql-5.4'}[0]->credentials
What does this mean? In the PHP docs we can read, that
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).
But how can the Object $dbObject be defined to allow ->{...}[...]access? Is this code kind of unsafe? Which PHP version does allow this?
Did I miss anything in the PHP docs?
It's to enable access to properties which would be invalid syntax as bare literals. Meaning:
$dbObject->mysql-5.4[0]->credentials
This is invalid/ambiguous syntax. To make clear to PHP that mysql-5.4 is a property and not a property minus a float, you need to use the {'..'} syntax.
To be exact, ->{..} enables you to use any expression as the property name. For example:
$dbObject->{ sprintf('%s-%.1f', 'mysql', 5.4) }
The curly brace syntax allows you to use a string literal or variable as a property or method name.
This is useful for several reasons:
(per #Deceze's answer): It allows you to access property names that would otherwise not be valid PHP syntax -- eg if the property name contains a dot or dash, per your example. Typically properties like this would be accessed via a __get() magic method, since they would also be invalid syntax to define as an actual property within the class.
(per #feela's answer): It allows you to use variables to reference your properties. This is similar to the $$ variable variable syntax. It's generally not really very good practice, but is useful in some cases.
(not mentioned by any other answers yet): It allows you to remove certain potential ambiguities from your code. Consider the following code for example:
$output = $foo->$bar['baz'];
This is ambiguous. You can resolve the ambiguity by adding braces or brackets:
$output = $foo->{$bar['baz']}; //gets the value of a property from $foo which has a name that is defined in $bar['baz']
$output = ($foo->$bar)['baz']; //gets the ['baz'] element of $foo->$bar array.
This is particularly important because the forthcoming relese of PHP 7 will change the default behaviour of code like like. This will make the language behave more consistently, but will break existing code that doesn't have the braces.
See also the PHP documentation for this change here: https://wiki.php.net/rfc/uniform_variable_syntax
But even without the language change to force the issue, code like this should have braces anyway to help with readability -- if you don't put braces, then you may end up struggling to work out what you were trying to do when you come back to the code in six months' time.
The curly braces syntax in the example is not from the array syntax, but comes from a possible syntax to access variables with variable names.
Curly braces may also be used, to clearly delimit the property name.
They are most useful when accessing values within a property that
contains an array, when the property name is made of mulitple parts,
or when the property name contains characters that are not otherwise
valid (e.g. from json_decode() or SimpleXML).
Examples from the PHP docs:
echo $foo->{$baz[1]} . "\n";
echo $foo->{$start . $end} . "\n";
echo $foo->{$arr[1]} . "\n";
See “PHP Variable variables”: http://php.net/manual/en/language.variables.variable.php
(More examples on the usage there…)
As an addition to #deceze's answer:
The -> operator means that you are accessing an object property. In this case the property name should be mysql-5.4 which is not valid PHP identifier (it must contain letters, numbers or underscores, see here). So it is 100% sure that the property name has been created dynamically.
PHP allows overloading properties using magic method called __get(). The body of this method allows you to handle any property you would wish - this can be any string, or any variable, even an object, which is cast to a string.
So in your case somebody created a class with a __get() magic method that handles string mysql-5.4. The curly braces { and } are given to denote that the string should be treated as property name (however there is no property with this name).
most of the time there is a $ after ->{ so it's like ->$variable
for example we have:
$languageCode = 'en';
$obj->{$languageCode};
$obj->{$languageCode} it is equivalent to $obj->en
============
in your case it's because it's not allowed in php write like:
$dbObject->mysql-5.4
because there is a - and there is a . in the mysql-5.4 and - and . makes a word to two words.
so you have to write it like this:
$dbObject->{'mysql-5.4'}[0]->credentials

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.

PHP variable variables in {} symbols

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

Categories