我有一些小问题。
我有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
类..它工作正常..我们是否有可能限制深度封装?
谢谢!
答案 0 :(得分:4)
根据您的示例,它将是:
$animal->dog->haaa();
但是,最好更改设计,以便Dog extends Animal
:
class Dog extends Animal {
public function scream(){
// do stuff
}
}
$dog = new Dog();
$dog->scream();
这更具语义性,因为狗属于动物“王国”。