Abstract

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 learn PHP 7?

Hacking with PHP has been fully updated for PHP 7, and is now available as a downloadable PDF. Get over 1200 pages of hands-on PHP learning today!

If this was helpful, please take a moment to tell others about Hacking with PHP by tweeting about it!

Next chapter: Iterating through object variables >>

Previous chapter: Final

Jump to:

 

Home: Table of Contents

Copyright ©2015 Paul Hudson. Follow me: @twostraws.