dongzhi8487 2012-11-14 17:28
浏览 145
已采纳

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

  • 写回答

3条回答 默认 最新

  • dongzhang3482 2012-11-14 17:30
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料