Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Abstract Classes and OOP Extras in PHP

DZone's Guide to

Abstract Classes and OOP Extras in PHP

To become a full-fledged developer, you'll probably have to have an understanding of OOP basics. And there's not time better to get started than the present.

· Web Dev Zone ·
Free Resource

Access over 20 APIs and mobile SDKs, up to 250k transactions free with no credit card required

Introduction

Last chapter of this series. If you have followed along with these blog posts you are now fully capable of creating projects using the Object Oriented paradigm.

In this part, we will learn how to use abstract classes and several other less common features of PHP such as reflection APIs and the singleton design pattern.

Follow the Series

This blog post is the sixth part of The Complete Guide to Object-Oriented Programming: Go from procedural programming to OOP expert in PHP

If you did not read the other parts yet

You can check the other blog posts following the links below

Abstract Classes

Abstract classes are very similar to interfaces but they have different rules that a web developer needs to be aware of.

The definition is quite straightforward, basically, an abstract class is a class that contains abstract methods. Abstract methods are methods that have been declared but not implemented in the code. This kind of class cannot be constructed as an object, in fact, they need to be extended. A ‘normal’ class that extends an abstract one must implement all methods that are inside the parent.

Something to notice is that a child class must define the abstract methods with the same or less restrictive visibility. This means that if in the abstract class there is a protected method it can be implemented only as a public or protected.

Another rule is that the number and type or required arguments need to be the same as the parameters.

abstract class Building {
    abstract protected function getWindowsCount();
    public function __construct()
    {
        echo “Building cannot be constructed”;
    }
}
class Office extends Building {
    public function getWindowsCount()
    {
        return 12;
    }
}
$myOffice = new Office;
// This command will return “Building cannot be constructed”
$myOffice->getWindowsCount();
// This command will return 12

There are no abstract methods within the Office class, thus, I can construct an object from it.

I have added a constructor inside the abstract class so that you will be aware of the fact that the parent’s constructor is called when the object is instantiated.

What is the difference between an interface and an abstract class?

To sum up, consider an interface as an empty shell. It has only signatures of the methods, which means the methods do not have a body.

An interface does not do anything, it is just a pattern, a set of methods that you need to replicate.

On the other hand, abstract classes are proper classes.

Even though they look like interfaces the have some specific characteristics.

You can specify their use by what they do and by a given method name.

Here is an example that highlights the differences between the two:

interface Building
{
     public function build();
     public function getWindowsCount();
}
class Office implements Building
{
    public $windows;
    public function build()
    {
        echo “Office built”;
    }
    public function getWindowsCount()
    {
        return $this->windows;
    }
}

In here, we are saying all the building should look like this than is up to the

abstract class Building
{
    public $windows;
    public function getWindowsCount()
    {
         return $this->windows;
    }
    abstract public function build();
}
class Office extends Building
{
    public function build()
    {
        echo “Office built”;
    } 
}

In an abstract class instead, we are saying that all the Building must have getWindowsCount().

Then we say that the method build() can be different, so we obligate the Office class to provide the implementation according to its needs.

Extra/Bonus

We have almost finished here with this introduction to Object Oriented programming in PHP.

Lots of information has been shared and I hope you understood all of it (if not just write your question below).

However, there are a few things that have been just quickly mentioned and I would love to go deeper and give you a wider comprehension on this topic.

Method Chaining

Method chaining is an OOP technique that permits the programmer to perform several different but connected actions in a sequential way.

Let’s break down this sentence.

“Perform different actions“ means calling different methods or functions:

Perform connected actions” can be translated into actions related to the same object or instance of the class.

In a sequential way” simply suggests that the methods are called one after another.

Here is an example that will clarify the concept:

class


{


class Building
{
    public $message;
    function __construct()
    {
        $this->message = "Foundation poured - ";
    }
    function stepOne()
    {
        $this->message .= "framing, plumbing, electrical and HVAC completed -";
        return $this;
    }
    function stepTwo()
    {
        $this->message .= "interior and exterior completed";
        return $this;
    }
    function getMessage()
    {
        return $this->message;
    }
}
$myHome = new Building();
echo $myHome->stepOne()->stepTwo()->getMessage();

All the method of the Building class have one trait in common and all of them return the object itself via the use of the keyword $this.

If you need to brush up, I have explained what the $this  keyword does in the introduction to Object-Oriented Programming.

The last command is chaining down all the methods of the class necessary to build up our sentence.

The outcome of the last command will look like this:

“Foundation poured — framing, plumbing, electrical and HVAC completed — interior and exterior completed.”

This is so easy that you can implement this to your code straight away without any problem, just be careful to return the object.

Autoloading

Any class must be defined before you need to use it, forget to do so will result in an error thrown.

Autoload alongside PSR-4 standards allows you to define them when a class is required.

I am sure that I do not need to say that this is an incredibly important feature.

In PHP, autoloading is done via the spl_autoload_register() that accepts a function as a parameter.

Just to explain how it works in detail I will need to write another article, so I will just give you an understandable example:

Given that the class you want to autoload is within the “classes/” path, here is what you would do.

This is more or less what happens behind the scene of most of the PHP frameworks out there.

function myAutoloader($className) {
    include 'classes/' . $className . '.php';
}
spl_autoload_register(myAutoloader);

spl_autoload_register has two more parameters:

  • One is a boolean and defines if the spl_autoload_register needed to throw exceptions when the autoload_function cannot be registered,

  • The other parameter is boolean as well and, if true, it will prepend the autoloader rather then attaching it.

If an error occurred and the function was not able to find the specified class, it will throw a fatal error.

Anonymous Classes

Wouldn’t it be great if PHP allowed the web developer to create and instantiate objects on the fly?

The release of PHP 7 included this present to the list of its features.

$myAnonymousBuilding = new class(“Main Street”)
{
    public function __construct(string $address)
    {
        echo “a new class has been constructed in ” . $address;
    }
}

Cool, right?

Notice how easy is to implement this class inline and that it can even accept parameters like a normal class.

The code in the example will output the string “a new class has been constructed in Main Street.”

The main use of an anonymous class is to extend a named class.

If, for instance, you need to override properties or methods, instead of declaring it, you can just create an in-line implementation in the same workflow you are currently using.

Reflection API

Reflection is a very useful feature that was introduced with the release of PHP 5.0 and became a standard later on in PHP 5.3.

This API permits you to examine PHP elements and fetch information about them at runtime.

For me, one of the most useful places to use the Reflection API is during automated testing, particularly during unit testing.

For example, when testing the values of private property in classes you can enter the properties via the API and then make assertions based on the test results.

There are different reflection classes, each of them allows you to inspect different types of variables.

Here are some classes:

  • ReflectionClass
  • ReflectionObject
  • ReflectionMethod
  • ReflectionFunction
  • ReflectionProperty

Below is a quick example of how the ReflectionClass is used:

$ReflectionObject = new ReflectionClass(“Building”);
print_r($ReflectionObject->getMethods());

This example will output an array of all the methods available within the Building class.

The parameter passed to  ReflectionClass can be of two types, either a string with the name of the class or a true instance of the class itself.

Each of the reflection classes have a few methods that allow you to retrieve different information about the element you are inspecting.

Singleton

Any self-respecting web developer will encounter design patterns on their way to mastering programming. Those patterns are nothing more than established methods that solve problems in a predefined way. 99% of PHP frameworks use them in order to increase the performances and the quality of the code.

If you have never heard the words design pattern here is your shot. I want to introduce you to the easiest among them all. We are, again,  going to use our imaginary city. We have had several Buildings, Offices, Schools, etc.

What about the city hall? The mayor needs to keep an eye on all these classes and instantiations and methods and properties.

In a city, there is only one mayor and they work in only one building, city hall.

There cannot be more that one city hall in a city.

Well… how do we add this rule in programming?

Through a singleton.

class cityHall
{
    private static $instance = null;
    private function __construct()
    {
        ...
    }
    public static function getInstance()
    {
        if (self::$instance == null){
            self::$instance = new Singleton();
        }
        return self::$instance;
    }
}

Here is it, this is an implementation of the singleton design pattern.

How does it actually work?

As you can see, the visibility of the constructor is set to private, so it blocks the creation of the object.

In order to create an instance of the class, you need to invoke the static method getInstance().

It checks if the instance has been already created, and, if not, it creates a new instance with the command:

self::$instance = new Singleton();

Otherwise, it just returns the object that has already been created.

The result is that, in this case, you are always going to have only one single cityHall in your code.

Where do we use the singleton design pattern in a real life use-case?

Singletons are very easy but they can also become problematic to deal with. Think of this design pattern whenever you must have a single instance of a class that has to be used in the long term.

An easy implementation could be, when creating a database class to connect a DB to the code, in the majority of the cases you are going to have only one database per project.

This is the perfect use for it.

Conclusion

If you have followed this article this has been quite a journey.

We have learned that Object-Oriented Programming or OOP is less difficult than it may seem from an outside perspective. The reality is that, as web developers, we love to use jargon. Properties, parameters, interfaces, abstract classes, dependency injection. Those words can give you a headache very quickly. However, by just continue on with a little bit at a time, you will find that applying this new knowledge is not only possible but easier than you thought.

What’s the Next Step?

If you understood the basic concepts of this article, you are ready to learn about PHP frameworks. There are plenty of them out there, and choose one of them can be overwhelming.

Below there is a really deep comparison that I wrote that compare 24 of them, you will not find anything similar elsewhere.

Guide to PHP frameworks.

#1 for location developers in quality, price and choice, switch to HERE.

Topics:
php ,object oriented programming ,oop ,web dev ,tutorial

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}