PHP Interface

PHP Interface

Last Updated on Mar 22, 2023

What is Interface?

Do you remember when we talked about Classes?

Interface is like a skeleton for the class. It doesn’t implement the functions. It just says what functions are needed. And what arguments should those functions get.

Let me show you an example

<?php
Interface Human{
    public function sayName();
    public function getAge(int $yearBorn);
}

As you can see we have not implemented those functions. We are just saying that if you are creating a human you should have these functions with those arguments.

Implement

Now if I want to create a class Man which is a human I tell php that I want to implement the functions in that skeleton

You’ll do this by using the word implements and the name of the interface

Class Man implements Human {
    
}

If you keep it like this, you will get an error. Php expects you to implement those functions so you have to do it.

Class Man implements Human
{
    public function sayName()
    {
        echo "my name is Amir";
    }
    public function getAge(int $yearBorn)
    {
        echo 'I am '.(date('Y') - $yearBorn).' years old';
    }
}

You can have other functions and other properties in that class. It doesn’t matter. As long as you implement the functions that have been specified in the interface you’re good to go.

Why Interface

You might say why on earth would I write the interface? I will write the class instead.

Well in small projects when you’re doing all the coding yourself it might not matter but when your project gets a little bigger or other developers start working on it as well, interface is your savior. It forces your code to keep organized and clean.

https://youtu.be/xEfPXG9sN9Q

Conclusion

Now you know about interface in PHP.

I recommend you to open a PHP files and create an interface. then define a class that implements that interface.

If you have any suggestions, questions, or opinions, please contact me. I’m looking forward to hearing from you!

Key takeaways

  • what is interface
  • how to implement the interface
  • why use interface

Category: programming

Tags: #php #oop

Join the Newsletter

Subscribe to get my latest content by email.

I won't send you spam. Unsubscribe at any time.

Related Posts

Courses