IMB
IMB

Reputation: 15889

How to return an array as object in PHP?

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?

Upvotes: 1

Views: 75

Answers (3)

tawfekov
tawfekov

Reputation: 5122

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

Upvotes: 1

arkascha
arkascha

Reputation: 42925

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.

Upvotes: 0

gen_Eric
gen_Eric

Reputation: 227270

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.

Upvotes: 7

Related Questions