Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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'];
share|improve this question
2  
It's return $this->contents;, right? – deceze Jul 23 '09 at 3:25
add comment (requires an account with 50 reputation)

2 Answers

up vote 3 down vote accepted

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())
share|improve this answer
How does array_pop know that it has to output 'id' ? – Ropstah Jun 9 '09 at 17:54
1  
array_pop will return the first element in the array, whether it's indexed numerically $x[0] or associatively $['id']. see 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 Jun 9 '09 at 18:06
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 Jun 9 '09 at 18:32
1  
array_pop returns the LAST element, not the first. – Jleagle Oct 17 '11 at 15:41
add comment (requires an account with 50 reputation)

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.

share|improve this answer
add comment (requires an account with 50 reputation)

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.