简体   繁体   English

PHP-当函数返回数组时,如何从数组中获取对象?

[英]PHP - How to get object from array when array is returned by a function?

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. 您应该使用2行版本。 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())

Keep it at two lines - if you have to access the array again, you'll have it there. 将其保留在两行中-如果您必须再次访问该阵列,则将其保存在该行中。 Otherwise you'll be calling your function again, which will end up being uglier anyway. 否则,您将再次调用函数,结果无论如何都会变得难看。

I know this is an old question, but my one line soulution for this would be: 我知道这是一个古老的问题,但是我的一句解决方法是:

PHP >= 5.4 PHP> = 5.4

Your soulution should work with PHP >= 5.4 您的解决方案应使用PHP> = 5.4

$id = $i->getContents()['id'];

PHP < 5.4 : PHP <5.4

class Item
{
    private $arrContents = array('id' => 1);

    public function getContents()
    {
        return $this->arrContents;
    }

    public function getContent($strKey)
    {
        if (false === array_key_exists($strKey, $this->arrContents)) {
            return null; // maybe throw an exception?
        }

        return $this->arrContents[$strKey];
    }
}

$objItem = new Item();
$intId   = $objItem->getContent('id');

Just write a method to get the value by key. 只需编写一种方法即可通过键获取值。

Best regards. 最好的祝福。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM