6.7.5 AbstractThis is NOT the latest copy of this book; click here for the latest version.
The abstract keyword is used to say that a function or class cannot be created in your program as it stands. This might not make sense at first - after all, why bother defining a class then saying no one can use it?
Well, it is helpful because it does not stop people inheriting from that abstract class to create a new, non-abstract (concrete) class.
Consider this code:
$poppy = new dog;
The code is perfectly legal - we have a class "dog", and we're creating one instance of that and assigning it to $poppy. However, given that we have actual breeds of dog to choose from, what this code actually means is "create a dog with no particular breed". Have you ever seen a dog with no breed? Thought not - even mongrels have breed classifications, which means that a dog without a breed is impossible and should not be allowed.
We can use the abstract keyword to back this up. Here is some code:
abstract class dog {
private $Name; // etc
$poppy = new dog;
The dog class is now abstract, and $poppy is now being created as an abstract dog object. The result? PHP halts execution with a fatal error, "Cannot instantiate abstract class dog".
As mentioned already, you can also use the abstract keyword with functions, but if a class has at least one abstract function the class itself must be declared abstract. Also, you will get errors if you try to provide any code inside an abstract function, which makes this illegal:
abstract class dog {
abstract function bark() {
print "Woof!";
}
}
It even makes this illegal...
abstract class dog {
abstract function bark() { }
}
Instead, a proper abstract function should look like this:
abstract class dog {
abstract function bark();
}
Author's Note: If it helps you understand things better, you can think of abstract classes as being quite like interfaces, which are discussed shortly.
|
Want to see this stuff in print? PHP in a Nutshell takes the core topics covered here, adds in thousands of edits from the editorial team and myself, and combines them to make an unbeatable reference for PHP programmers at all levels.
My latest book has hundreds more tips on how to use PHP, Apache, and MySQL, plus Perl, Python, shell scripts, performance tuning, and more!
|