2014-02-07 114 views
0

我有一個小問題。封裝問題

我有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類..它工作正常..我們是否有深度封裝的限制?

謝謝!

回答

4

根據您的例子那就是:

$animal->dog->haaa();

但是,它可能是最好的改變設計,使Dog extends Animal

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

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

這是更多的語義,因爲狗屬於動物「王國」。

+0

是的..這是真的......糟糕的錯誤-_-「謝謝你! –