views:

1061

answers:

2

Hi,

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'];
+2  A: 

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())
Zack
How does array_pop know that it has to output 'id' ?
Ropstah
array_pop will return the first element in the array, whether it's indexed numerically $x[0] or associatively $['id']. see http://php.net/array_pop for more on how it works. Now, if your class can do further manipulation to the private variable $contents then this may not be reliable, but based on what you have here array_pop will give you the contents of $contents['id']
artlung
Ok well the class is a bit bigger then displayed :). I ended up creating a Item($index) function which returns the item. $i->getContents()->Item('id');
Ropstah
+3  A: 

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.

Andy Mikula