php - Encapsulation issues

33

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 gethaaa() function.. with

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

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

Thank you!

285

Answer

Solution:

Based on your example it would be:

$animal->dog->haaa();

However, it might be best to change the design so thatDog 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".

People are also looking for solutions to the problem: php - How to restrict specific google user can read/write the google sheet?

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.