Thursday, July 17, 2014

Interface in PHP

Basic Concept
Interface is declared as same as class, except interface having only function declarations without any definition. A class which implementing a interface must be defined all functions which are declared in interface. We can implement a interface using the keyword implements.

Example 1: Simple Interface Concept.
<?php
interface BasicAction
{
        public function grow();
}

class Man implements BasicAction
{
        public function speak()
        {
               echo 'Will Speak';        
        }

        public function grow()
        {
               echo 'Will Grow';        
        }
}

$obj=new Man();
$obj->speak();
$obj->grow();
?>

Example 2: Extend a interface on another interface.

interface BasicAction
{
        public function grow();
}

interface Animal extends BasicAction
{
        public function walk();
}

class Deer implements Animal
{
        public function walk()
        {
               echo 'Will Walk';        
        }

        public function grow()
        {
               echo 'Will Grow';        
        }
}

Example 3: Multiple inheritance of interfaces on a class

interface A
{
        public function fun1();
}

interface B
{
        public function fun2();
}

class Test implements A, B
{
        public function fun1()
        {
               echo 'Fun 1 Definition';
        }

        public function fun2()
        {
               echo 'Fun 1 Definition';
        }
}

Interface Characters
1. All functions on interface must be public.
2. All functions on interface must be defined in classes which are implements interface.
3. We can inherit more than one interface on a class using comma(,) separator.
4. We can extend a interface on other interface.
5. We can declare constants inside a interface. Which will work as constants under class, except we cannot overwrite constants on other class or interface which implements or extends this interface.
6. Prior to PHP 5.3.9, a class could not implement two interfaces that specified a method with the same name, since it would cause ambiguity. More recent versions of PHP allow this as long as the duplicate methods have the same signature.

No comments:

Post a Comment

Learn JavaScript - String and its methods - 16

<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>String and it's methods - JS&l...