Object Interfaces

Getting Started with PHP
Getting Started with PHP : Home
Introduction
Installation
Hello World
Data Types in PHP
Variables in PHP
Operators in PHP
Decision Making in PHP
Iterations in PHP
Functions in PHP
Arrays in PHP
Strings in PHP
Object Oriented PHP
Classes and Objects
Constructors
Inheritance
Object Interfaces
Static and Final
Advanced Features in PHP
GET and POST
Session in PHP
Cookies in PHP
Server Variables

Interface
In Interfaces you can declare all the methods that you want a class to implement. All the methods in Interface has no statements i.e. only signatures are there. Interfaces are declared using interface keyword.
Instead to inherting we implement interfaces while using in a new class and that class must implement all those methods, failure to do so will result in fatal error.
Unlike inheritance you can implement more than one interfaces in PHP using , to seperate multiple interfaces.
Interfaces may have constants but not Variables.

<?php
interface clickHandler{
	// No statements only Signatures
    function leftClick($x,$y);
    function rightClick($x,$y);
    function scroll();
}
 
class clickHandling implements clickHandler{
//Implementing functions
 
    function leftClick($x,$y){
        echo "left click at $x, $y<br>";
    }
    function rightClick($x,$y){
        echo "right click at $x, $y<br>";
    }
    function scroll(){
        echo "Scrolled<br>";
    }
// creating a new function other than interface
 
    function customInput($a){
        echo "Input is $a<br>";
    }
}
// Creating Object
 
$handler = new clickHandling();
 
$handler->leftClick(3,7);
$handler->rightClick(12,43);
$handler->scroll();
$handler->customInput("abc");
?>


Output
left click at 3, 7
right click at 12, 43
Scrolled
Input is abc

You can inherit an interface to create another interface by using extends instead of implements.

Login to Track Your Progress