note 95404 modified in language.oop5.abstract by danbrown

From: Date: Tue, 11 Oct 2011 19:51:33 +0000
Subject: note 95404 modified in language.oop5.abstract by danbrown
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-183822@lists.php.net to get a copy of this message
Here's an example that helped me with understanding abstract classes. It's just a very simple way of explaining it (in my opinion). Lets say we have the following code: <?php class Fruit { private $color; public function eat() { //chew } public function setColor($c) { $this->color = $c; } } class Apple extends Fruit { public function eat() { //chew until core } } class Orange extends Fruit { public function eat() { //peel //chew } } ?> Now I give you an apple and you eat it. <?php $apple = new Apple(); $apple->eat(); ?> What does it taste like? It tastes like an apple. Now I give you a fruit. <?php $fruit = new Fruit(); $fruit->eat(); ?> What does that taste like??? Well, it doesn't make much sense, so you shouldn't be able to do that. This is accomplished by making the Fruit class abstract as well as the eat method inside of it. <?php abstract class Fruit { private $color; abstract public function eat(); public function setColor($c) { $this->color = $c; } } ?> Now just think about a Database class where MySQL and PostgreSQL extend it. Also, a note. An abstract class is just like an interface, but you can define methods in an abstract class whereas in an interface they are all abstract. --was-- Here's an example that helped me with understanding abstract classes. It's just a very simple way of explaining it (in my opinion). Lets say we have the following code: <?php class Fruit { private $color; public function eat() { //chew } public function setColor($c) { $this->color = $c; } } class Apple extends Fruit { public function eat() { //chew until core } } class Orange extends Fruit { public function eat() { //peel //chew } } ?> Now I give you an apple and you eat it. <?php $apple = new Apple(); $apple->eat(); ?> What does it taste like? It tastes like an apple. Now I give you a fruit. <?php $fruit = new Fruit(); $fruit->eat(); ?> What does that taste like??? Well, it doesn't make much sense, so you shouldn't be able to do that. This is accomplished by making the Fruit class abstract as well as the eat method inside of it. <?php abstract class Fruit { private $color; abstract public function eat() public function setColor($c) { $this->color = $c; } } ?> Now just think about a Database class where MySQL and PostgreSQL extend it. Also, a note. An abstract class is just like an interface, but you can define methods in an abstract class whereas in an interface they are all abstract. http://php.net/manual/en/language.oop5.abstract.php

« previous php.notes (#183822) next »