什么时候应该使用 stdClass ,什么时候应该在 php oo 代码中使用数组? [英] When should I use stdClass and when should I use an array in php oo code?

查看:31
本文介绍了什么时候应该使用 stdClass ,什么时候应该在 php oo 代码中使用数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在工作中进行大规模重构的过程中,我希望引入 stdClass ***** 作为从函数返回数据的一种方式,并且我正在尝试寻找非主观参数来支持我的决定.

In the middle of a period of big refactorings at work, I wish to introduce stdClass ***** as a way to return data from functions and I'm trying to find non-subjectives arguments to support my decision.

在什么情况下最好使用一种而不是另一种??

Are there any situations when would it be best to use one instead of the other ??

使用 stdClass 而不是数组有什么好处??

What benefits would I get to use stdClass instead of arrays ??

有些人会说函数必须尽可能少且具体才能返回单个值.我决定使用 stdClass 是暂时的,因为我希望从长远来看为每个进程找到正确的值对象.

推荐答案

通常的做法是

  • 在返回具有固定分支的定义数据结构时使用对象:

  • Use objects when returning a defined data structure with fixed branches:

 $person
   -> name = "John"
   -> surname = "Miller"
   -> address = "123 Fake St"

  • 返回列表时使用数组:

  • Use arrays when returning a list:

      "John Miller"
      "Peter Miller"
      "Josh Swanson"
      "Harry Miller"
    

  • 在返回结构化信息列表时使用对象数组:

  • Use an array of objects when returning a list of structured information:

      $person[0]
        -> name = "John"
        -> surname = "Miller"
        -> address = "123 Fake St"
    
      $person[1]
        -> name = "Peter"
        -> surname = "Miller"
        -> address = "345 High St"
    

  • 对象不适合保存数据列表,因为您总是需要一个键来寻址它们.数组可以实现两种功能——保存任意列表和数据结构.

    Objects are not suitable to hold lists of data, because you always need a key to address them. Arrays can fulfill both functions - hold arbitrary lists, and a data structure.

    因此,如果您愿意,可以在第一个和第三个示例的对象上使用关联数组.我想说这真的只是风格和偏好的问题.

    Therefore, you can use associative arrays over objects for the first and third examples if you want to. I'd say that's really just a question of style and preference.

    @Deceze 就何时使用对象(验证、类型检查和未来方法)提出了许多优点.

    @Deceze makes a number of good points on when to use an object (Validation, type checking and future methods).

    这篇关于什么时候应该使用 stdClass ,什么时候应该在 php oo 代码中使用数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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