Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

ShamiCanCode's avatar

oop interface

Why we use interfaces when we have to implement functions in derived class?

0 likes
11 replies
Sinnbeck's avatar

An example. You can inject the interface and use the service container to set the proper implementation

Take 5 different cache drivers. If all implement the same interface, you know that the expected methods exist

ShamiCanCode's avatar

@Sinnbeck no not in laravel in general give me an example that I will understand nd why we use interfaces ?

Sinnbeck's avatar

@ShamiCanCode same thing. Your method expects an interface. You can then pass any class that implements that interface.

In an app I manage we can export to pdf or PowerPoint. The method for creating it all just expects a class that implements the PresentationExport interface

public function export(PresentationExport $exporter)
{

} 
Sinnbeck's avatar

@ShamiCanCode that no matter what class I get I can be absolutely sure they have implemented the needed methods.

Sinnbeck's avatar

@ShamiCanCode not sure how to answer that. Interfaces does not make sense without classes. Classes implements interfaces. That's the whole point

Sinnbeck's avatar

@ShamiCanCode not sure how else I can explain it. I gave a real world example. There are other examples of using it, but my real world example is a simple one

1 like
Lumethys's avatar

@ShamiCanCode the answer is "enforcing a structure"

by using an interface, you would establish a structure for ALL the underlying classes. The reason? 5 years down the line, some new developer go in and had to make a new class, they will have the same structure.

You may ask: Can't that new developer just look at the code and replicate the structure without using an interface? The answer is yes, but it will take more time, and is more error-prone. If you use an interface, they are FORCED to use the same structure, with full IDE support, so why not?

for example, lets take a look at an interface to define classes that handle database connection:

interface DBConnect{
	abstract public function connect()
}

and then you have a class that implement that interface:

class LocalDBConnect implements DBConnect{
	public function connect(){
		//do something
	}
}

2 years down the line, you need to add a Cloud DB connection:

class CloudDBConnect implements DBConnect{
	//notice you MUST have a method called connect()
	public function connect(){
		//do something different
	}
}

if you dont have an interface to define the structure ( in this case: must have 1 method call connect()), someone can call the method access():

	public function access(){
		//do something different
	}

and all you code that use connect will break

Please or to participate in this conversation.