PHP 8.5.0 Alpha 4 available for testing

Voting

: two minus one?
(Example: nine)

The Note You're Voting On

mbajoras at gmail dot com
15 years ago
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.

<< Back to user notes page

To Top