Classes and OOP (Part 5)

1.0 Previous Tutorial

This is the fifth tutorial in a series of tutorials on classes and OOP.

First Tutorial
Second Tutorial
Third Tutorial
Fourth Tutorial

In the previous tutorial we learned about interfaces, their use in the programming world and multiple different ways we could use them (such as extending one or multiple interfaces or implementing 1 or more interfaces).

1.1 Tutorial Introduction

In this tutorial we would dwell into something similar to interfaces but not exactly. What I'm talking about is abstract classes and functions. In my view, abstract classes are more advanced.

By definition, the word 'abstract' means "existing in thought or as an idea but not having a physical or concrete existence." (Source: Google).

That is what we had in interfaces... those named methods (without a body) are abstract, because they exist, but don't have a concrete physical existence. Just a name.

function abstract_function();

We are not going to use the file we were finished off with in the previous tutorial, but we are going to use the file we were left off with in the third tutorial of this series.

<?php
class fruit
{

    private $amount = 2;

    public function __construct()
    {
        echo "Picking up a(n) {$this->fruit}.<br />\n";
    }

    public function eat()
    {
        $this->prepare();
        $this->chew();
        $this->swallow();
    }

    public function amount($number)
    {
        if($number < 11)
        {
            $this->amount = $number;
        }
    }

    public function __destruct()
    {
        echo "We ate a total of {$this->amount} {$this->fruit}(s).<br />\n";
    }

}

class apple extends fruit
{

    protected $fruit = 'apple';

    protected function prepare()
    {
        echo "Washing the apple.<br />";
    }

    protected function chew()
    {
        echo "Biting the apple.<br />";
        echo "Chewing the apple.<br />";
    }

    protected function swallow()
    {
        echo "Swallowing the apple.<br />";
    }

}

class banana extends fruit
{

    protected $fruit = 'banana';

    protected function prepare()
    {
        echo "Peeling the banana.<br />";
    }

    protected function chew()
    {
        echo "Biting the banana.<br />";
        echo "Chewing the banana.<br />";
    }

    protected function swallow()
    {
        echo "Swallowing the banana.<br />";
    }

}

$fruit = 'banana';

$product = new $fruit();

$product->eat();
?>

2.0 Abstract Classes

An abstract class is a sort of an advanced interface. It's purpose is the same as interfaces and it adds more functionality and provides for more uses then interfaces.

Abstract classes lay out the outline for how other child classes extending it should look like. Just like an interface, all of the classes named in an abstract class has to be present in the child class extending it with the body for the class. In essence, it's like fill in the blanks... the abstract class provides the idea of the class while the extending child classes fills in the blanks.

On top of having named functions in an abstract class, you could also have a full function with body and everything. If you have a fully named and defined function in an abstract class you don't put it in the child class extending the abstract class. You also (if you need to) may over-ride functions in a child class that you have named and defined in an abstract class.

To make the class abstract, you use the keyword abstract before the word 'class' when you start writing the class (e.g: abstract class fruit). In an abstract class, all the functions that are just named (without the body), needs to have the keyword abstract in front of the function (e.g: abstract function prepare()).

Unlike an interface where you could only have public methods, in an abstract class you could also have protected methods as well. You still can't have a private method in an abstract class because a private method means that no other class can touch it, but in this case, there would be a child class that is forced to have a function named like that, so the strictest access level you can use in an abstract class is protected.

You can have private functions/members in an abstract class if you only use it in the abstract class and not in the child class extending it. For instance the variable $amount in our abstract class we are only using within the abstract class (function 'amount()' is available for us to use without defining it in the child class). Same thing with functions, we could have them private only if we are using them in the abstract class and not in the child class.

We need to add the keyword abstract to the class 'fruit' that we are using (provided at the top). So now our 'fruit' class looks like:

abstract class fruit
{

    private $amount = 2;

    public function __construct()
    {
        echo "Picking up a(n) {$this->fruit}.<br />\n";
    }

    public function eat()
    {
        $this->prepare();
        $this->chew();
        $this->swallow();
    }

    public function amount($number)
    {
        if($number < 11)
        {
            $this->amount = $number;
        }
    }

    public function __destruct()
    {
        echo "We ate a total of {$this->amount} {$this->fruit}(s).<br />\n";
    }

}

There's that keyword abstract that we are using to tell the PHP engine/parser that the class is abstract. If you actually try to run the script with that class, it will work, but we are not done here.

We are using 3 functions in the child classes that the abstract class is not enforcing us to use (besides in the 'eat()' function). Those functions are 'prepare()', 'chew()' and 'swallow()'. Let's add those to the class after the function 'amount()'.

    protected abstract function prepare();

    protected abstract function chew();

    protected abstract function swallow();

I want to point out here that it doesn't matter in what order you put the keywords in. You could have just as easily done 'abstract protected function prepare()' instead of 'protected abstract function prepare()' and it would work just the same.

Now what we have done is named and defined all of the functions in the abstract class 'fruit' that would be used in all the child classes (or relevant to all of the child classes), and just named all of the functions that the child classes needed to define.

We also made three functions 'protected', meaning that they can not be touched outside of the class, bringing the enforcement of our ordering into play here (as we had in our third tutorial).

If you define an abstract member of an abstract class protected, the same member in the child class must be defined in the same or less restrictive access level. This means if our method 'prepare()' is made 'protected' in the abstract class, when we define it in the child class, we could name it as either 'protected' or 'public', but not 'private'.

If you don't define an access level in the abstract class, then it is assumed that the method is public, and in the child class, you would only be able to define those methods as public.

2.1 Multiple Abstract Classes

It is possible for an abstract class to extend an abstract class (just like an interface extending an interface). Unlike interfaces though, you can't extend more then one abstract class (means no delimited lists 😟 ). For example, the following abstract class.

abstract class food
{

    protected abstract function prepare();

    protected abstract function chew();

    protected abstract function swallow();

}

abstract class fruit extends food
{

    private $amount = 2;

    public function __construct()
    {
        echo "Picking up a(n) {$this->fruit}.<br />\n";
    }

    public function eat()
    {
        $this->prepare();
        $this->chew();
        $this->swallow();
    }

    public function amount($number)
    {
        if($number < 11)
        {
            $this->amount = $number;
        }
    }

    public function __destruct()
    {
        echo "We ate a total of {$this->amount} {$this->fruit}(s).<br />\n";
    }

}

You also can't extend more then one abstract class with a child like you could with an interface.

2.2 Static Context

If you remember previously we were talking about writing methods in a static context and how to use such classes. It is also (as a reminder) bad practice (in most cases) as it puts the static members in a global scale, voiding OOP encapsulation.

What I want to point out in this section is that you could (if you need to) have static members in an abstract class, but only if that member is defined (has a body, and not just named [just the signature]). For example, the following code has two members... one that could be static and one that can't. The one member that can be static has the keyword static in front of it, and the one that can't, doesn't. (This code is not part of our tutorial file).

abstract class car
{

    // This is just a signature (a named function)
    abstract function make();

    // This is a fully defined function
    abstract static function drive()
    {   
        // This function has a body
        echo "Vrooooom!";
    }
}

2.3 Instantiation

I want to point out here that just like interfaces, you can't instantiate an abstract class like you would be able with any other class. For example, the following code would fail because the class 'fruit' is an abstract class.

<?php
$product = new fruit();

$product->eat();
?>

This is another powerful thing about abstract classes (and interfaces). For instance, if we had a function 'taste()' which we would call to see how an apple or a banana tastes, it wouldn't make any sense if we ask the class 'fruit' on how a 'fruit' tastes. It would make sense if we ask a class 'apple' (which is extending the abstract class 'fruit') on how an 'apple' tastes. The same with the class 'banana'.

2.4 Inheritance and Hierarchy

If you remember from the third tutorial where the parent not being able to inherit the members of a child class or a grandparent not being able to inherit the members of a parent and child class (the parent class being a child class to the grandparent class), that changes a little bit here. (If you haven't noticed that already).

If you already have noticed that in the abstract class 'fruit' we have a function named 'eat()' and in that function, we are calling on three functions defined in the child classes. In this case, the parent does inherit the child's members and can use them in it's own functions.

It's also true if you are extending an abstract class with another abstract class. The parent abstract class inherits the abstract child's members and can use those members in it's own functions. For instance, if we change our abstract class 'food' and 'fruit' to the following, it would still work fine.

abstract class food
{

    protected abstract function prepare();

    protected abstract function chew();

    protected abstract function swallow();

    public function eat()
    {
        $this->devour();
    }

}

abstract class fruit extends food
{

    private $amount = 2;

    public function __construct()
    {
        echo "Picking up a(n) {$this->fruit}.<br />\n";
    }

    protected function devour()
    {
        $this->prepare();
        $this->chew();
        $this->swallow();
    }

    public function amount($number)
    {
        if($number < 11)
        {
            $this->amount = $number;
        }
    }

    public function __destruct()
    {
        echo "We ate a total of {$this->amount} {$this->fruit}(s).<br />\n";
    }

}

3.0 Abstract VS Interface

While it may seem like interfaces and abstract classes or similar, there are differences between them. Below are some key differences between an abstract class and an interface (Source: StackOverflow).

  • Abstract classes can have constants, members, method stubs and defined methods, whereas interfaces can only have constants and methods stubs.
  • Methods and members of an abstract class can be defined with any visibility, whereas all methods of an interface must be defined as public.
  • When inheriting an abstract class, a concrete child class must define the abstract methods, whereas an an abstract class can extend another abstract class and abstract methods from the parent class don't have to be defined.
  • Similarly, an interface extending another interface is not responsible for implementing methods from the parent interface. This is because interfaces cannot define any implementation.
  • A child class can only extend a single abstract (or any other) class, whereas an interface can extend or a class can implement multiple other interfaces.
  • A child class can define abstract methods with the same or less restrictive visibility, whereas a class implementing an interface must define the methods with the exact same visibility.

Mainly, an interface doesn't care how you come up with the public methods (the methods that would be accessed outside of the class). It just cares about the public methods (the signatures in the interface/named functions).

An abstract class is the same, with the addition of sharing functions with child classes. Since in some systems, different modules may have certain similarity (for instance a database access wrapper), the abstract class would contain the function signatures (mostly the public methods used to access the functions) like an interface would, plus contain the similarities.

Those similarities might be protected (not accessible outside of class) since they are specific for the class/function and shouldn't be messed with outside of class.

For example we have a database access wrapper. There are different kinds of databases, such as MySQL and SQLite (there are others, but for the sake of simplicity, our example contains two). We would use an abstract class named 'database' and then have a child class 'MySQL' and 'sqlite' which would be extending the abstract class 'database'.

Both of those databases/servers would have public methods connect, query and close (plus others, but for the sake of simplicity of the example, we'll only have these three), so the abstract class would only have a signature for those functions... it would just name them. Both of those servers would need to sanitize the input and they would be done the same way.

So the function 'sanitize()' would be defined in the abstract class and used in the child 'query()' function to sanitize the input that is to be queries.

3.1 Abstracts Implementing Interfaces

There is also such a thing when an abstract class implements an interface. This is also useful if you have different abstract classes that would (should) be used the same way.

For instance, an interface would be 'food' and an abstract class implementing would be 'fruit' with the class 'banana' extending the abstract class fruit. Then we have an abstract class 'dessert' implementing the interface 'food' with the class 'iceCream' extending the abstract class 'dessert'. You would have the functions 'prepare()', 'chew()', 'swallow()' and 'eat()' for all of them since you do that to everything that is food, but the way you go about doing it would be different.

For example (not part of the tutorial file, but you could run it if you want to):

<?php
interface food
{

    function eat();

}

abstract class fruit implements food
{

    private $amount = 2;

    public function __construct()
    {
        echo "Picking up a(n) {$this->fruit}.<br />\n";
    }

    public function eat()
    {
        $this->prepare();
        $this->chew();
        $this->swallow();
    }

    public function amount($number)
    {
        if($number < 11)
        {
            $this->amount = $number;
        }
    }

    public function __destruct()
    {
        echo "We ate a total of {$this->amount} {$this->fruit}(s).<br />\n";
    }

}

class apple extends fruit
{

    protected $fruit = 'apple';

    protected function prepare()
    {
        echo "Washing the apple.<br />";
    }

    protected function chew()
    {
        echo "Biting the apple.<br />";
        echo "Chewing the apple.<br />";
    }

    protected function swallow()
    {
        echo "Swallowing the apple.<br />";
    }

}

$product = new apple();

$product->eat();
?>

You would notice that in our interface we only have one function defined 'eat()'. That is because all members of the interface must be public, otherwise it's not an interface any more. The interface is the middleman between the class and the user, so all members defined needs to be public so the user can access them.

If you ever need to or want to, you could implement more than one interface by making a comma delimited list after the word 'implements':

abstract class fruit implements food, product

4.0 Our File

Our file at the end of this tutorial should look like:

<?php
abstract class food
{

    protected abstract function prepare();

    protected abstract function chew();

    protected abstract function swallow();

    public function eat()
    {
        $this->devour();
    }

}

abstract class fruit extends food
{

    private $amount = 2;

    public function __construct()
    {
        echo "Picking up a(n) {$this->fruit}.<br />\n";
    }

    protected function devour()
    {
        $this->prepare();
        $this->chew();
        $this->swallow();
    }

    public function amount($number)
    {
        if($number < 11)
        {
            $this->amount = $number;
        }
    }

    public function __destruct()
    {
        echo "We ate a total of {$this->amount} {$this->fruit}(s).<br />\n";
    }

}

class apple extends fruit
{

    protected $fruit = 'apple';

    protected function prepare()
    {
        echo "Washing the apple.<br />";
    }

    protected function chew()
    {
        echo "Biting the apple.<br />";
        echo "Chewing the apple.<br />";
    }

    protected function swallow()
    {
        echo "Swallowing the apple.<br />";
    }

}

class banana extends fruit
{

    protected $fruit = 'banana';

    protected function prepare()
    {
        echo "Peeling the banana.<br />";
    }

    protected function chew()
    {
        echo "Biting the banana.<br />";
        echo "Chewing the banana.<br />";
    }

    protected function swallow()
    {
        echo "Swallowing the banana.<br />";
    }

}
$fruit = 'apple';

$product = new $fruit();

$product->eat();
?>

4.1 Conclusion

In this tutorial we learned about class abstraction. We also learned the difference between an interface and an abstract class and when to use which.

This page was published on It was last revised on

Contributing Authors

0

0 Comments

  • Votes
  • Oldest
  • Latest