我正在使用模板引擎在我想要的网站中插入代码.
我写了一个函数来测试一些非常简单的东西:
myfunction() { return '($this->data["a"]["b"] ? true : false)'; }
Run Code Online (Sandbox Code Playgroud)
问题是,$ this-> data是私有的,我无法在任何地方访问它,所以我必须使用getData(); 这导致我的问题.
$this->getData()['a']['b']
Run Code Online (Sandbox Code Playgroud)
不起作用,并且首先分配值也不会因为它将直接在if()块中使用.
有任何想法吗?
在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) 我不确定这是否可能,但如果它是......我无法弄清楚如何做到这一点
我想从一个函数返回的数组中获取一个特定的元素,而不是先将它传递给一个数组......就像这样......
$item = getSomeArray()[1];
function getSomeArray(){
$ret = Array();
$ret[0] = 0;
$ret[1] = 100;
return $ret;
}
Run Code Online (Sandbox Code Playgroud)
这个的正确语法是什么?
反正有没有临时变量直接访问数组中返回的数据?
目前,我的代码如下:
function getData($id) {
// mysql query
return mysql_fetch_array($result);
}
$data = getData($id);
echo $data['name'];
Run Code Online (Sandbox Code Playgroud)
是否有直接的方法来获取没有临时变量的返回数据?