如何在PHP中将数组作为对象返回?

如何在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?

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.

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.

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