PHP Interface


In PHP, an interface helps to achieve an abstraction. An interface contains only a declaration.

 

An interface consists of abstract methods and final variables.


Syntax:

interface interface_name1{
	// declare constant fields  
    // declare methods that abstract 
}
interface interface_name2{
	// declare constant fields  
    // declare methods that abstract 
}
class class_name implements interface_name1,interface_name2{
	// fields  
	// methods 
} 

Example:-

<?php
// Interface Roll
interface Roll {
    const rollno = 10;  
}

// Interface Name
interface Name {
    const name = "Sundarrajan";  
    public function showdata();
}

// Student implements both interfaces
class Student implements Roll, Name {
    public function showdata() {
        echo self::rollno . " " . self::name . "\n";
    }
}

// Main execution
$s1 = new Student();
$s1->showdata();
?>

Difference between Abstract Class and Interface.

Abstract Class Interface
An abstract class can have both declaration and definition. An interface can have declaration only.
Does not support multiple inheritance. Supports multiple inheritance.
An abstract class has final, non-final, static and non-static variables. An interface has static and final variables.
To declare an abstract class using abstract keyword. To declare an interface using interface keyword.
An abstract class can extend another class. An interface can extend another interface.
An abstract class can have both abstract and non-abstract methods. The interface has abstract methods only.



OnlineTpoint is a website that is meant to offer basic knowledge, practice and learning materials. Though all the examples have been tested and verified, we cannot ensure the correctness or completeness of all the information on our website. All contents published on this website are subject to copyright and are owned by OnlineTpoint. By using this website, you agree that you have read and understood our Terms of Use, Cookie Policy and Privacy Policy.