Php, composite pattern, is it bad when child knows about parent?

后端 未结 1 479
隐瞒了意图╮
隐瞒了意图╮ 2021-01-29 15:10

given this code:

class Parent
{
    public function getAdata()
    {
        return array(1,2,3,4);
    }

    public function getChild()
    {
        return ne         


        
1条回答
  •  一生所求
    2021-01-29 15:49

    There is no parent-child relationship here at all. You merely instantiate one class and pass it an instance of another class. There's no problem with that at all, and it doesn't mean those classes are in any sort of relationship.

    What is bad about the example is that you hardcode Child inside of Parent. That makes Child a hardcoded dependency which cannot be substituted or externally controlled, and hence may cause problems in the future with testing or refactoring code. You should look into dependency injection instead.

    0 讨论(0)
提交回复
热议问题