Friday, January 6, 2017

Interfaces – PHP OOP Tutorial - 2

Abstract Classes – PHP OOP Tutorial

courtesy : http://jaskokoyn.com/2013/06/09/abstract-classes/


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 Pet class for a bit. Mostly because we don’t need to use abstract classes in our Pet class. So, create a new file and insert this bit of code.
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.
The abstract keyword 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 ingredients as 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.
Now, let’s go back to our file that includes both of these files and add this line of code.
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.
You should get an error like so.
Fatal Error: Class Cookie contains 1 abstract method and must therefore be declared abstract or implement the remaining methods.
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.

No comments:

Post a Comment