This tutorial is a part of the PHP OOP tutorial series. If you would like to view the complete list of tutorials under this series and the order you should follow, then click here. http://jaskokoyn.com/php-oop-tutorial-series/

Today, we’ll be discussing what abstract classes are and how we could use them. There will be times where you’ll create a class that you don’t want anyone to use directly, but instead extend it. Let’s take a closer look at this

Creating Abstract Classes

We’re going to deviate from our Petclass for a bit. Mostly because we don’t need to use abstract classes in our Petclass. So, create a new file and insert this bit of code.

1

2

3

4

<?php

include('classes/recipe.class.php');

include('classes/cookie.class.php');

?>

We include 2 files that contain classes which we haven’t created yet. They’re also stored in a folder called classes. Let’s create the recipe class first. Insert this bit of code in your recipe.class.php file.

1

2

3

4

5

6

<php

abstractclassRecipe

{

abstractpublicfunctioningredients();

}

?>

The abstractkeyword is introduced here. This keyword tells PHP that this class is an abstract class. You’ll notice that we not only define our class abstract, but our method ingredientsas well. An abstract method DOES NOT contain a body.

Things may be confusing right now, but you’ll see what this does in a bit. Let’s create our cookie class. In your cookie.class.php file, add this bit of code.

1

2

3

4

5

6

7

8

9

<?php

classCookieextendsRecipe

{

publicfunctioningredients()

{

}

}

?>

Now, let’s go back to our file that includes both of these files and add this line of code.

1

newRecipe();

You should get an error like so

Fatal Error: Cannot instantiate abstract class Recipe

This is because you can not create instances of abstract classes. Abstract classes are meant to be used as templates or a base for classes that will extend it.

If you try to create an instance of the cookie class, you’ll get no errors. Let’s remove the ingredients method from the cookie class and then try creating an instance of it like so.

When your class contains abstract methods, PHP will force classes that extend an abstract class to also define it’s abstract methods. This is one of the benefits of using abstract classes. You’re forcing your developers to define certain methods because it’ll order them to follow a certain logic or structure.

Why not just create any ordinary class?

While you can pass through life coding classes that aren’t abstract, it sometimes isn’t the best practice to not have structured and organized code. Abstract classes are there to help make sure developers follow certain rules.

Conclusion

It’s up to you on when and how to use abstract classes. Usually they’re helpful when you find yourself creating classes that follow similar logic. This way you don’t find yourself writing the same thing over and again with different names. To learn more about abstraction, then go here.