简体   繁体   中英

Encapsulation issues

I have a tiny issues.

I have 3 classes:

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';
    }
}

I'm trying to get haaa() function.. with

 $animal = new Animal();
 $animal->haaa();

If the function haaa() is into the Dog class.. it works fine.. Is it possible that we have a limit of deep encapsulation?

Thank you!

Based on your example it would be:

$animal->dog->haaa();

However, it might be best to change the design so that Dog extends Animal :

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

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

That's more semantic, since dogs belong to the animal "kingdom".

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM