Explain this fragment of PHP for me: returning array and immediately reference an index
<?php
function ReturnArray() {
return array('a' => 'f', 'b' => 'g', 'c' => 'h', 'd' => 'i', 'e' => 'j');
}
echo ${!${!1}=ReturnArray()}['a']; // 'f'
?>
Please explain what's the logic and step o开发者_开发技巧f compute with those ${!1} in the above resolution that works well.
Let's start with some basics. In PHP, something like hello
will evaluate to the string "hello"
. To reference a variable, you can use this syntax: ${expr}
. There's also a shorthand for this, $foo
, which will roughly evaluate to this: ${"foo"}
.
Also, you probably know that you can assign multiple variables at once: $a=$b=$c='hello';
, for example. This will assign $a
, $b
, and $c
to 'hello'
. This is actually represented as $a=($b=($c='hello')));
. $foo=value
is an expression which, after $foo
is set, will evaluate to value
.
Your code statement looks like this:
echo ${!${!1}=ReturnArray()}['a'];
The first thing it does, obviously, is call ReturnArray
. It then evaluates !1
, which evaluates to false. The ${!1}
therefore makes a variable with the name false
, though not a string(?!). After that, it applies a not operation to the array. All non-empty arrays are truthy, so the not operation changes it to false
. It then uses that ${}
syntax again to retrieve the variable named false
. It then uses an array access to retrieve the value in the array for key 'a'
.
I hope that made sense.
!1
= false${!1}
= NULL${!1} = ReturnArray()
= array('a' => 'f', 'b' => 'g', 'c' => 'h', 'd' => 'i', 'e' => 'j')- so now $NULL contains array
and again we see construction${!(condition)
which means $NULL (see first and second points), so we can convert it to: $NULL['a']
(and $NULL contains array)
You can easily check this:
print_r(${NULL});
- you'll see array ;)
${!1}
evaluates to ${false}
!${false = ReturnArray()}
evaluates to $true = array('a' => 'f', /* etc */)
.
echo $true['a']
produces 'f'
as 'f'
corresponds to index 'a'
I'm curious now, what is this from?
Meanwhile I've located an answer so I post it here:
echo ${!${!1}=ReturnArray()}['a'];
${!${!1}=ReturnArray()}['a']
!1 resolves to false.
${!${false}=ReturnArray()}['a']
false resolves to... I don't know. Let's just say false resolves to a variable "a".
${!$a=ReturnArray()}['a']
$a is now the array. The ! changes the returned array into the boolean false (like: if (!$handle = fopen('x', 'r')) { echo 'connection failed' }.
${false}['a']
I don't know what false resolves to, but we're using again variable "a".
$a['a'] // this is trivial
IMHO, it's mostly pure noise. The code assigns an array to a variable and then retrieves key a
, which is obviously f
. I just uses booleans to generate the intermediate variable names and let PHP cast them to strings.
精彩评论