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

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

问题描述

在工作中进行大量重构的中间,我希望引入stdClass *****作为从函数返回数据的一种方式,并且我试图找到非主观论据来支持我的决定. /p>

在任何情况下,最好使用一种而不是另一种吗?

使用stdClass代替数组有什么好处?


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

解决方案

通常的方法是

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

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

  • 返回列表时使用数组:

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

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

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

对象不适合保存数据列表,因为您始终需要一个密钥才能对其进行寻址.数组可以同时实现两个功能-容纳任意列表和数据结构.

因此,如果需要,可以将对象的关联数组用于第一个和第三个示例.我会说,这实际上只是样式和偏好的问题.

@Deceze在何时使用对象方面有很多好处(验证,类型检查和将来的方法).

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 ??

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


Some would say that functions have to be as little and specific to be able to return one single value. My decision to use stdClass is temporal, as I hope to find the right Value Objects for each process on the long run.

解决方案

The usual approach is

  • 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 makes a number of good points on when to use an object (Validation, type checking and future methods).

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

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