Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In PHP, what does the ${$ } syntax do?

Tags:

syntax

php

I ran across this inside a WordPress plugin.

$stuff = $wpdb->get_results(" assume valid database query here ");
foreach ($stuff as $cur)
    ${$cur->type}[] = $cur->name;

$stuff will be an object containing more objects of database rows. These database rows will have columns 'id', 'type', and 'name'. The 'type' column will contain one of these three strings: 'file', 'url', or 'code'.

It looks like this code snippet will potentially create or add new elements to arrays named $file, $url, and/or $code. However, I'm not familiar with this use of the ${$ } syntax; I've only seen it inside double quoted strings to avoid parsing problems.

Am I correct in my analysis of this code? Where can I learn more about this use of the ${$ } syntax?

There is a question about the ${ } syntax inside a double-quoted string. I understand that use, but I'm specifically asking about a second $ character inside the { } braces.

like image 242
Ben Miller - Remember Monica Avatar asked Dec 26 '22 22:12

Ben Miller - Remember Monica


1 Answers

Consider

$foo = 42;
$a = 'foo';
echo $$a; // Prints 42

That´s called a variable variable, since the variable´s name is determinated at runtime. But is $$a[1] the same as ${$a[1]} or the same as {$$a}[1]? The brackets avoid that ambiguity, just like they do when dealing with operator precedence in math.

like image 178
Zsolt Szilagyi Avatar answered Dec 30 '22 10:12

Zsolt Szilagyi