Accessing an array element when returning from a function
Some searching throug开发者_JS百科h Google (and my own experience) shows that in PHP you can't grab an array element when it's been returned from a function call on the same line. For example, you can't do:
echo getArray()[0];
However, I've come across a neat little trick:
echo ${!${false}=getArray()}[0];
It actually works. Problem is, I don't know why it works. If someone could explain, that would be great.
Thanks.
echo ${!${false}=getArray()}[0];
This is how it works, step by step
${false}=getArray()
assigns the result of getArray to a variable with an empty name ('' or null would work instead of false)
!${false}=getArray()
negates the above value, turning it to boolean false
${!${false}=getArray()}
converts the previous (false) value to an (empty) string and uses this string as a variable name. That is, this is the variable from the step 1, equal to the result of getArray.
${!${false}=getArray()}[0];
takes index of that "empty" variable and returns an array element.
Some more variations of the same idea
echo ${1|${1}=getArray()}[1];
echo ${''.$Array=getArray()}[1];
function p(&$a, $b) { $a = $b; return '_'; }
echo ${p($_, getArray())}[1];
As to why getArray()[0]
doesn't work, this is because php team has no clue how to get it to work.
it works because your using the braces to turn the value into a varialbe, heres an example.
$hello = 'test';
echo ${"hello"};
Why is this needed, this is needed encase you want to turn a string or returned value into a variable, example
${$_GET['var']} = true;
This is bad practise and should never be used IMO.
you should use Objects if you wish to directly run off functions, example
function test()
{
$object = new stdClass();
$object->name = 'Robert';
return $object;
}
echo test()->name;
It should be noted that you can do this as of PHP 5.4. From the manual on array dereferencing:
As of PHP 5.4 it is possible to array dereference the result of a function or method call directly. Before it was only possible using a temporary variable.
Example:
function theArray() {
return range(1, 10);
}
echo theArray()[0];
// PHP 5.4+: 1
// PHP -5.4: null
Pre PHP 5.4: Attempting to access an array key which has not been defined is the same as accessing any other undefined variable: an E_NOTICE-level error message will be issued, and the result will be NULL.
Manual:
- http://www.php.net/manual/en/language.types.array.php#example-89
精彩评论