Database results as objects or arrays?

前端 未结 4 747
礼貌的吻别
礼貌的吻别 2020-12-17 17:48

This question is similar to Mysql results in PHP - arrays or objects? However, my question expands on what has been discussed there.

I\'m trying to decide which form

4条回答
  •  长情又很酷
    2020-12-17 18:37

    It’s preference at the end of the day. Personally, I prefer objects. Although CakePHP uses arrays for results using the “object” name as the array key. However, things start to get funny when you fetch related records in CakePHP.

    With your problem, you could simply have objects within objects. For example:

    stdClass Object
    (
        [id] => 1
        [title] => Article Title
        [published] => 2013-03-04 16:30:00
        [category] => stdClass Object
            (
                [id] => 1
                [name] => Category Name
            )
    
    )
    

    You can then display associated data in your views as follows:

    category->name; ?>
    

    Or if you use getters and setters:

    getCategory()->getName(); ?>
    

    There’s no right or wrong answer. As I say, it’s all personal preference.

提交回复
热议问题