I've been working in various companies and I've seen different reasons for using PHP interfaces. I would like to hear your opinion, what do you think in which cases should we use PHP interfaces, the reason behind using interface?

Recommended Answers

All 5 Replies

I read most of that but it didn't give me the answer. Maybe I should ask: "How do I recognize whether I should use interface or not?"

The answer lies in what PHP Interfaces do for us. Another answer is you don't have to use it. Here's the paragraph that sums up why we would use it:

Interfaces allow you to define/create a common structure for your classes – to set a standard for objects. Interfaces solves the problem of single inheritance – they allow you to inject 'qualities' from multiple sources. Interfaces provide a flexible base/root structure that you don't get with classes.Aug 26, 2006 - https://www.killerphp.com/articles/php-interfaces/

Nothing forces you to do this. It's your choice but it could help if your code has grown unweildy.

You can implement multiple inheritance using interaces.

Example

Class Student implements AlumniInterface, SportsClubInterface, MusicClubInterface {

// say is each interface have methods like  findAlumniInMNC(), accestoGym(), accessToMusicInstruments()

}
// a object of the class student will have access to all of above methods
$john = new student();

"How do I recognize whether I should use interface or not?"

The most common usage of interfaces is when you find you need to create different (unrelated) classes to have similar required functionality.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.