// 狗 classDog{ function__construct ($name) { $this->name = $name; } publicfunctionsay_hello () { echo"Hello my name is " . $this->name; } } // 黑狗 classBlackDog{ function__construct ($name) { $this->name = $name; } publicfunctionsay_hello () { echo"Hello my name is " . $this->name; } publicfunctionrun () { echo"Yo! I am running"; } } $dog = new Dog('dog'); $black_dog = new BlackDog('black dog'); $dog->say_hello(); // Hello my name is dog $black_dog->say_hello(); // Hello my name is black dog $black_dog->run(); // Yo! I am running
雖然沒什麼問題,但在工程師的世界不是有句名言嗎:
DRY(Don’t Repeat Yourself)
既然它們都是「狗」,而黑狗只是多了跑步這個功能,那幹嘛不直接讓它「繼承」狗就好?就跟現實中的小孩會繼承父母 DNA 是一樣的感覺。
classDog{ function__construct ($name) { $this->name = $name; } public functionsay_hello () { echo "Hello my name is " . $this->name; } } // 繼承狗的 Class classBlackDogextendsDog{ public functionrun () { echo "Yo! I am running"; } } $dog = new Dog('dog'); $black_dog = new BlackDog('black dog'); $dog->say_hello(); // Hello my name is dog $black_dog->say_hello(); // Hello my name is black dog $black_dog->run(); // Yo! I am running
classDog{ function__construct ($name) { $this->name = $name; } public functionsay_hello () { echo "Hello my name is" . $this->name; } } classBlackDogextendsDog{ // 直接寫一樣的來覆蓋 public functionsay_hello() { echo "yoyoyo black dog is better"; } public functionrun () { echo "Yo! I am running"; } } $dog = new Dog('dog'); $black_dog = new BlackDog('black dog'); $dog->say_hello(); // Hello my name is dog $black_dog->say_hello(); // yoyoyo black dog is better