r/PHPhelp • • Nov 17 '22

Solved PHP Abstract Classes, PHP Interfaces

I read about it online and still can't understand what these two is about. How does it work and when do you use these two? Can someone give example and explain these to me in simple words? Thanks!

8 Upvotes

9 comments sorted by

View all comments

10

u/ZippyTheWonderSnail Nov 17 '22

An interface is simply a template for building a class. It does not contain code inside functions. It merely defines which need to appear in implemented classes. It's generally used to ensure all classes of a certain type obey a common naming convention.

Imagine you need to connect a database. The interface defines the functions classes can use to make database calls, regardless of the database. So even if the database changes (say from MySQL to PostgreSQL), it doesn't matter. The function names will be the same, and the data returned with be the same.

https://www.php.net/manual/en/language.oop5.interfaces.php

interface Template 
{
    public function doSomething(int $id): string
    public function doAnotherThing(string $email): bool
}

class myClass implements Template
{
    public function doSomething(int $id): string
    {
        // Do something and return a string
    }
    
    public function doAnotherThing(string $email): bool
    {
        // Do something and return a boolean (true / false)
    }
}

class mySecondClass implements Template
{
    public function doSomething(int $id): string
    {
        // Do something else and return a string
    }
    
    public function doAnotherThing(string $email): bool
    {
        // Do something else and return a boolean (true / false)
    }
}