Interface Class

We know that an interface is defined by the interface keyword and all methods are abstract. All methods declared in an interface must be public; this is simply the nature of an interface.

Here is an example:

In an interface, the method body is not defined, just the name and the parameters. If we do not use an interface, what problems will be encounter? Why should we use interface ?

You’ll get answers to these questions in this article. Please see the code below:

In the above example, I do not use interface . I write to the log using the LogToFile class.

But, if I want to write a log using LogToDatabase , I have to change the hard-coded class reference in the above code on line number 23.

That line code is:

public function __construct(LogToFile $logger)

This code will be:

public function __construct(LogToDatabase $logger)

In a large project, if I have multiple classes and I need to change them, I have to change all the classes manually.

But, if we use an interface, this problem is solved; we will not need to change code manually.

Now, see the following code and try to understand what happens if I use interface :

Now, if I change from LogToDatabase to LogToFile , I do not have to change the constructor method manually. In the constructor method, I have injected an interface ; not an arbitrary class.

If you have multiple classes and swap from one class to another class, you will get the same result without changing any class references.

In the above example, I write the log using LogToDatabase and now I want to write the log using LogToFile .

I can call it like this:

$controller = new UsersController(new LogToFile);

$controller->show();