为什么要返回对象而不是数组? [英] Why return object instead of array?

查看:151
本文介绍了为什么要返回对象而不是数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在WordPress中做了很多工作,而且我注意到返回数组的函数要多于数组.除非您特别要求一个数组,否则数据库结果将作为对象返回.错误作为对象返回.在WordPress之外,大多数API都会为您提供一个对象而不是数组.

I do a lot of work in WordPress, and I've noticed that far more functions return objects than arrays. Database results are returned as objects unless you specifically ask for an array. Errors are returned as objects. Outside of WordPress, most APIs give you an object instead of an array.

我的问题是,为什么他们使用对象而不是数组?在大多数情况下,这并不重要,但是在某些情况下,我发现对象不仅难以处理而且难以缠住.使用对象有性能上的原因吗?

My question is, why do they use objects instead of arrays? For the most part it doesn't matter too much, but in some cases I find objects harder to not only process but to wrap my head around. Is there a performance reason for using an object?

我是一个自学成才的PHP程序员.我拥有文科学位.因此,如果我错过了计算机科学的一个基本方面,请原谅我. ;)

I'm a self-taught PHP programmer. I've got a liberal arts degree. So forgive me if I'm missing a fundamental aspect of computer science. ;)

推荐答案

这些是我通常更喜欢对象的原因:

These are the reasons why I prefer objects in general:

  • 对象不仅包含数据,还包含功能.
  • 对象具有(在大多数情况下)预定义的结构.这对于API设计非常有用.此外,您可以将属性设置为public,protected或private.
  • 对象更适合面向对象的开发.
  • 在大多数IDE中,自动补全仅适用于对象.

以下是一些要阅读的内容:

Here is something to read:

  • Object Vs. Array in PHP
  • PHP stdClass: Storing Data in an Object Instead of an Array
  • When should I use stdClass and when should I use an array in php5 oo code
  • PHP Objects vs Arrays
  • Mysql results in PHP - arrays or objects?
  • PHP objects vs arrays performance myth
  • A Set of Objects in PHP: Arrays vs. SplObjectStorage
  • Better Object-Oriented Arrays

这篇关于为什么要返回对象而不是数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆