I've been reading an PHP5 book, and the author commonly used this syntax
${"{$something}_somethingelse"};
I have no idea what that means. Does it dynamically generate a variable name?
Someone help me out?
It is a language feature called Variable variables.
Consider the following piece of code:
$a = 'hello';
This is pretty straight forward. It creates the variable $a and sets its value to 'hello'.
Let's move on with:
$$a = 'world';
${$a} = 'world';
Basically, since $a = 'hello', those two statement are the equivalent of doing:
$hello = 'world';
So the following:
echo "$a ${$a}";
Is the equivalent of doing:
echo "$a $hello";
Braces { }
The braces are used to prevent ambiguity problems from occurring. Consider the following:
$$a[1] = 'hello world';
Do you want to assign a variable named after the value of $a[1] or do you want to assign the index 1 of the variable named after $a?
For the first choice, you would write it as such:
${$a[1]} = 'hello world';
For the second choice:
${$a}[1] = 'hello world';
Your example
Now, for your example.
Let's consider that:
$something = 'hello';
Using your example as such:
${"{$something}_somethingelse"} = 'php rocks';
Would essentially be equivalent of doing:
$hello_somethingelse = 'php rocks';
They are 'variable variables'. See this.
Brackets allow you to make more advanced variable names. It your Case if $something was equal to test it would be:
${"test_somethingelse"};
Which is just an advanced variable name.
Here is an example.
$test = "test";
${"test_test"} = "test2";
echo $test; // prints test
echo ${"test_test"}; // prints test2
Using Variable Varaibles, as everyone else mentioned, you can create variables based on other variables. So in your case, he was making a variable based on $something's value
$something = "test";
${"{$something}_somethingelse"};
turns into
${"test_somethingelse"};
That will replace the {$something} with the value of $something.
I think the inner curly braces are just for readability and to help when doing $object->property etc.
Because it seems to be also in a variable, that is called a variable variable.
For example,
$foo = 'bar';
$$foo = 7;
echo $bar;
// produces 7;
Related
I've been studying PHP for a little while now, and I ran across variable manipulation functionality officially called Variable Variables. The basic syntax is:
$foo = 'bar';
$$foo = 'foo2';
The result of these two statements is $foo equals bar, and a new variable, $bar equals foo2.
I expect that if variable $foo contained a number, this would throw some sort of error. What happens if the value of $foo is originally set to an invalid variable name? What error will be thrown?
No error will be thrown.
The PHP Docs on Variables states that variables must match the following regex:
[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*
However this rule is only enforced by the parser. PHP supports variables named anything, the parser just enforces certain naming conventions.
You can check it yourself:
$foo = '1';
$$foo = 'baz';
print_r(get_defined_vars());
/*
Prints:
Array
(
...
[foo] => 1
[1] => baz
)
*/
You can try it with this simple script:
<?php
$foo='1';
$$foo='hello world';
echo $$foo;
?>
and this one:
<?php
$foo='1';
$$foo='hello world';
echo $1;
?>
Basically, no error will be thrown if you do this. However, you must access the new variable as $$foo, not as $1. If you run both scripts, the first one will say "hello world" and the second will give an error in the log file.
EDIT: Thanks #FabrÃcio Matté for saying that you can access it like this:
<?php
$foo='1';
$$foo='hello world';
echo ${1};
?>
I'm new to OOP in PHP and I find the difference between the following two expressions difficult to understand.
$object->$foo;
$object->foo;
Maybe it's my fault, but I could not find the relevant part in the manual.
The first call $obj->$foo is using a so called variable variable. Check this:
class A {
public $foo = 1;
}
$a = new A();
$foo = 'foo';
// now you can use both
echo $a->$foo;
echo $a->foo;
Follow the manual about variable variables
Well, in order to fully understand the somewhat odd-looking $object->$foo, you should understand two things about PHP:
Variable names
Most of the time variables in PHP are quite straight-forward. They begin with a $ sign, have one [a-zA-Z_] character, and then any amount of [a-z-A-Z0-9_] characters. Examples include:
$var = 'Abcdef';
$_GET = [];
$a1 = 123;
// And so on...
Now, PHP variables can actually be named pretty much anything, as long as the name is, or can be cast to, a scalar type. The way you name a variable with anything is to use curly braces ({}), like this:
${null} = 'It works'; echo ${null};
${false} = 'It works'; echo ${false};
${'!'} = 'It works'; echo ${'!'};
// Slightly weirder...
${(int)trim(' 5 ')} = 'It works'; echo ${5};
${implode(['a','b','c'])} = 'It works'; echo $abc;
Important: Just because you can do this does not mean you should, however. It is mostly just an oddity of PHP that you can do this.
Variable variables
A somewhat convoluted explanation: A variable variable is a variable that is accessed using a variable name.
A much easier way to understand variable variables is to use what we just learning about variable names in PHP. Take this example:
${"abc"} = 'Abc...';
echo $abc;
We create a variable using the string, "abc", which can also be accessed using $abc.
Now, there is no reason (or rule) that says it has to be a string.... it can also be a variable:
$abc = 'Abc...';
$varName = 'abc';
echo ${$varName}; // echo $abc
That is basically a variable variable. "Real" variable variables just do not use the curly braces:
$abc = 'Abc...';
$varName = 'abc';
echo $$varName; // echo $abc
As for the question
In the question the $object->$foo thing is basically just an "object variable variable", if you like
$object = new stdClass;
$object->abc = 'The alphabet!';
$foo = 'abc';
echo $object->$foo;
echo $object->{$foo}; // The same
echo $object->{'abc'}; // The same
Object variable variables can be somewhat useful, but they are rarely necessary. Using an associative array is usually a better choice.
Alright, I'm trying to understand how this PHP code works.
<?php
$test = "success";
$primary = "test";
$id = ${$primary};
echo $id;
?>
I know the output is "success" but I don't understand how it works.
What i understand so far:
test variable has the string "success",
primary variable has the string "test",
'id' variable has the string of the first variable in the list (the test variable),
print the string in the 'id' variable.
I'm confused because i don't know what the primary variable is doing in the braces within the id variable.
A simple explanation would be appreciated.
This is a concept called variable variables.
It means that at runtime, if multiple variable indicators $ are present, PHP will attempt to associate them in a cascading manner.
For example, take the following:
$a = "b";
$b = "c";
$c = "d";
echo $$$a;
PHP will systematically go through the echo statement to determine what the actual value is, as such:
$$$a is equivalent to $$("b") (because $a is "b")
...which is equivalent to $("c") (because $b is "c")
...which is finally equivalent to "d"
In your example, you're given a variable assignment to something that, in essence, is like ${$a}. In PHP, braces are used to isolate variables within strings, but can be used on their own to denote a variable explicitly, so ${$a} is exactly equivalent to $$a in this case.
$id = ${$primary};
try to parse from right to left $primary = 'test'
so ${$primary} is now $test
so equation becomes $id = $test;
$id = $test = success
Know more about variables variables on the link provided by other users
This is a variable variable.
$test = "success";
$primary = "test";
//${$primary} means $test here, because value of $primary is "test".
//It is equal to $$primary
$id = ${$primary};
echo $id; //Prints "success"
http://php.net/manual/en/language.variables.variable.php
The title may be a little confusing. This is my problem:
I know you can hold a variable name in another variable and then read the content of the first variable. This is what I mean:
$variable = "hello"
$variableholder = 'variable'
echo $$variableholder;
That would print: "hello". Now, I've got a problem with this:
$somearray = array("name"=>"hello");
$variableholder = "somearray['name']"; //or $variableholder = 'somearray[\'name\']';
echo $$variableholder;
That gives me a PHP error (it says $somearray['name'] is an undefined variable). Can you tell me if this is possible and I'm doing something wrong; or this if this is plain impossible, can you give me another solution to do something similar?
Thanks in advance.
For the moment, I could only think of something like this:
<?php
// literal are simple
$literal = "Hello";
$vv = "literal";
echo $$vv . "\n";
// prints "Hello"
// for containers it's not so simple anymore
$container = array("Hello" => "World");
$vv = "container";
$reniatnoc = $$vv;
echo $reniatnoc["Hello"] . "\n";
// prints "World"
?>
The problem here is that (quoting from php: access array value on the fly):
the Grammar of the PHP language only allows subscript notation on the end of variable expressions and not expressions in general, which is how it works in most other languages.
Would PHP allow the subscript notation anywhere, one could write this more dense as
echo $$vv["Hello"]
Side note: I guess using variable variables isn't that sane to use in production.
How about this? (NOTE: variable variables are as bad as goto)
$variablename = 'array';
$key = 'index';
echo $$variablename[$key];
I need to make a dynamic variable based on a loop, what i am looking for is a variable something like
$var = "foo";
$$var = "bar";
echo $foo; // bar
but for me it should be more like a fixed parameter attached to the dynamic part like
$var='123';
$'current_'.$$var=some value; // not correct syntax
echo $current_123 should give 'some value';
Use curly braces:
$${'current_' . $var} = $some_value;