封装问题

时间:2014-02-07 21:06:27

标签: php oop encapsulation

我有一些小问题。

我有3个班级:

Class Animal {
    public $dog;
    function __construct() {
        $this->dog = new Dog();
    }
}
Class Dog {
    public $scream;
    function __construct() {
        $this->scream = new Scream();
    }
}
Class Scream {
    public $scream;
    function __construct() {
    }
    public haaa(){
       return 'hello World';
    }
}

我正试图通过

获取haaa()功能..
 $animal = new Animal();
 $animal->haaa();

如果函数haaa()进入Dog类..它工作正常..我们是否有可能限制深度封装?

谢谢!

1 个答案:

答案 0 :(得分:4)

根据您的示例,它将是:

$animal->dog->haaa();

但是,最好更改设计,以便Dog extends Animal

class Dog extends Animal {
  public function scream(){
    // do stuff
  }
}

$dog = new Dog();
$dog->scream();

这更具语义性,因为狗属于动物“王国”。