我有一个返回数组的函数。为了返回该数组的值,我做了这样的事情:
$obj->methodname()[keyvalue];
这仅适用于 php 5.4。我想让这段代码在较低的 php 版本中工作。
我的代码:
class ObjectTest {
public $ar;
function __construct() {
$this->ar = array(
1 => 'beeldscherm',
2 => 'geluidsbox',
3 => 'toetsenbord',);
}
public function arr(){
return $this->ar;
}
}
$obj = new ObjectTest();
//by calling the method and putting square brackets and the key of the element
var_dump($obj->arr()[2]);
我已经重写了较低版本的代码,如下所示:
public function arr($arg = null){
if(is_null($arg)){
return $this->ar;
}
return $this->ar[$arg];
}
我怀疑这个解决方案是否优雅。你会说什么?有什么更好的解决方案吗?
你可以这样做,将数组存储在变量中,然后访问特定的数组索引。
$arrList = var_dump($obj->arr());
echo $arrList[2];