解引用函数结果的PHP语法
背景
在我经常使用的所有其他编程语言中,在不声明一个新变量来保存函数结果的情况下,对函数的返回值进行操作是很简单的。
然而,在PHP中,这似乎并不是那么简单:
示例1(函数结果是数组)
<?php
function foobar(){
return preg_split('/\s+/', 'zero one two three four five');
}
// can php say "zero"?
/// print( foobar()[0] ); /// <-- nope
/// print( &foobar()[0] ); /// <-- nope
/// print( &foobar()->[0] ); /// <-- nope
/// print( "${foobar()}[0]" ); /// <-- nope
?>
示例2(函数结果是一个对象)
<?php
function zoobar(){
// NOTE: casting (object) Array() has other problems in PHP
// see e.g., http://stackoverflow.com/questions/1869812
$vout = (object) Array('0'=>'zero','fname'=>'homer','lname'=>'simpson',);
return $vout;
}
// can php say "zero"?
// print zoobar()->0; // <- nope (parse error)
// print zoobar()->{0}; // <- nope
// print zoobar()->{'0'}; // <- nope
// $vtemp = zoobar(); // does using a variable help?
// print $vtemp->{0}; // <- nope
有人能建议如何在PHP中这样做吗?
素胚勾勒不出你
哆啦的时光机