在php中,我经常需要使用数组来映射变量......但我似乎无法在一个内联中执行此操作.cf示例:
// the following results in an error:
echo array('a','b','c')[$key];
// this works, using an unnecessary variable:
$variable = array('a','b','c');
echo $variable[$key];
Run Code Online (Sandbox Code Playgroud)
这是一个小问题,但它每隔一段时间就会不停地窃听......我不喜欢这样一个事实:我没有使用变量;)
背景
在我定期使用的每种其他编程语言中,操作函数的返回值很简单,而不会声明一个新变量来保存函数结果.
但是,在PHP中,这看起来并不那么简单:
<?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
?>
Run Code Online (Sandbox Code Playgroud)
<?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"? …Run Code Online (Sandbox Code Playgroud) 我想在不使用额外变量的情况下做这样的事情:
class className {
public static function func(){
return array('true','val2');
}
}
if(className::func()[0]) {
echo 'do?ru';
} else {
echo 'Yanl??';
}
Run Code Online (Sandbox Code Playgroud) 我在下面使用以下代码:
$data = array();
$value = reset($value);
$data[0] = (string) $value->attributes()['data'];
------^
Run Code Online (Sandbox Code Playgroud)
我在localhost中没有问题,但在其他主机中,当我检查代码时,我看到了这个错误:
解析错误:语法错误,意外'['in ....
我已经显示了代码导致错误的位置.
我也用过:
$data[] = (string) $value->attributes()['data'];
Run Code Online (Sandbox Code Playgroud)
(没有0在[])
我怎么解决呢?