1
function myfunc ()
{
    $a['foo'] = 'bar';
    $a['baz'] = 'qux';

    return $a;
}

How do you do it so that when you call $a = myfunc(); you can use echo $a->foo; and it will output bar?

Additional question: Having that simple function above, is it better to return an array or object?

7
  • 2
    "Better" is subjective. Better for what purpose? Commented Nov 14, 2012 at 17:30
  • @deceze I guess my question is what is more efficient in terms of use of system resources in the same comparison that single quotes is faster than double quotes. Commented Nov 14, 2012 at 17:33
  • 1
    @IMB: Have a look at this: phpbench.com Commented Nov 14, 2012 at 17:35
  • @Rocket That site is interesting, but mostly missing the point. isset vs. empty vs. is_array is entirely pointless, for instance, since they all do very different things and are used in different situations. Don't choose which to use based on minuscule performance differences. Commented Nov 14, 2012 at 17:43
  • @deceze: I was mostly trying to show that single vs double quotes is silly and you shouldn't worry. Commented Nov 14, 2012 at 17:57

3 Answers 3

7

Just cast it as an object.

function myfunc ()
{
    $a['foo'] = 'bar';
    $a['baz'] = 'qux';

    return (object)$a;
}

As for which one you want, it's up to you. It depends on what you are doing with the returned object or array.

Sign up to request clarification or add additional context in comments.

Comments

1

1-I would do it like this :

function myfunc ()
{
    $a['foo'] = 'bar';
    $a['baz'] = 'qux';
    $array = new ArrayObject($a);
    return $array;
}

ArrayObject is supported form php version 5

2- doesn't really matter if you return array or object , its your decision

Comments

0

If you return an array you will have to access the member as $a['foo']. The -> is indeed an oop operator. To use this you would need to create an object instead of an array, but that means you have to define a class first. This again means that the two members foo and baz must be present for all instanciations of such an object. So that is a completely different thing.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.