PHP - 如何从数组对象数组时由函数返回? [英] PHP - How to get object from array when array is returned by a function?
本文介绍了PHP - 如何从数组对象数组时由函数返回?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我怎样才能得到一个数组对象时该阵列由函数返回?
类项目{
私人$内容=阵列('ID'=> 1); 公共职能getContents(){
返回$内容;
}
}$ I =新项目();
的$ id = $ I-GT&; getContents()['身份证']; //这是不是有效?//我知道这是可能的,但我一直在寻找一个1行的方法..
$内容= $ I-GT&; getContents();
的$ id = $内容['身份证'];
解决方案
您应该使用2行版本。除非你有一个令人信服的理由,壁球您code下来,没有任何理由的不的有这个中间值。
不过,你可以尝试像
的$ id = array_pop($ I-GT&; getContents())
how can I get a object from an array when this array is returned by a function?
class Item {
private $contents = array('id' => 1);
public function getContents() {
return $contents;
}
}
$i = new Item();
$id = $i->getContents()['id']; // This is not valid?
//I know this is possible, but I was looking for a 1 line method..
$contents = $i->getContents();
$id = $contents['id'];
解决方案
You should use the 2-line version. Unless you have a compelling reason to squash your code down, there's no reason not to have this intermediate value.
However, you could try something like
$id = array_pop($i->getContents())
这篇关于PHP - 如何从数组对象数组时由函数返回?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文