When should I use stdClass and when should I use an array in php oo code?

前端 未结 7 507
太阳男子
太阳男子 2020-11-29 00:33

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 argu

7条回答
  •  半阙折子戏
    2020-11-29 00:51

    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).

提交回复
热议问题