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

I was wondering if there is a way to return an array value from a function that returns an array inline. So if I have a function like:

class MyObj
{
    public function myFunction()
    {
         return array('arrayIndex'=>'myValue');
    }
}

I would like to be able to do this:

$object = new MyObj();
$myValue = $object->myFunction()['arrayIndex']; //but this doesn't work

rather than this:

 $object = new MyObj();
 $myArray = $object->myFunction();
 $myValue = $myArray['arrayIndex'];

Simple question but I just don't know if its possible to reference it in a similar way. So yay or nay?

share|improve this question
 
Please do your homework before posting a question. You find it in the manual here: php.net/manual/en/language.types.array.php#example-87 –  hakre May 1 '12 at 15:28

3 Answers

up vote 4 down vote accepted

Upgrade to PHP 5.4 and you can then do array dereferencing.

share|improve this answer
1  
You can? Finally! :-) –  Rocket Hazmat May 1 '12 at 14:51

What about

class MyObj
{
    public function myFunction($index)
    {
        $your_array = array('arrayIndex'=>'myValue');
        return $your_array[$index];
    }
}


f$object = new MyObj();
$myValue = $object->myFunction('arrayUndex');
share|improve this answer
class MyObj
{
    public function myFunction()
    {
         return array($one,$two);
    }
}


f$object = new MyObj();
list($first,$second) = $object->myFunction();
share|improve this answer

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.