Ropstah
Ropstah

Reputation: 17804

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'];

Upvotes: 1

Views: 11110

Answers (3)

Raisch
Raisch

Reputation: 821

I know this is an old question, but my one line soulution for this would be:

PHP >= 5.4

Your soulution should work with PHP >= 5.4

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

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.

Upvotes: 0

Andy Mikula
Andy Mikula

Reputation: 16780

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.

Upvotes: 3

Zack Marrapese
Zack Marrapese

Reputation: 12090

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())

Upvotes: 4

Related Questions