-2

use interface in php

Interface

➔ Interface in object oriented is a template, which allows us to create a framework for one or more objects

➔ Looking at the interface, we can completely determine which methods and fixed attributes (or constants) are present in the object that implements it.

➔ Syntax:

<?php
Interface InterfaceName
{
// code to do
}
?>

Interface properties

➔ Interface is not an object

➔ In the interface we are only declaring methods, not defining them.

◆ In the interface we can declare a constant but can not declare the variable.

◆ An interface can not be initialized (because it is not an object).

◆ Implement interface classes must declare and redefine the methods contained in that interface.

◆ A class can implement multiple interfaces.

◆ Interfaces can inherit each other.

Use Interface

➔ Create interface

➔ Create class implements interface

➔ The class defines the contents of the functions

<?php
interface Animal
{
public function getName();
}
{
private $name;
public function getName() {
return $this->name;
}
}
?>

Use Interface

<?php
interface Animal
{
    public function getName();
}

interface Buffalo
{
    public function checkHorn();
}

public class TheCalf implements Animal, Buffalo
{
    private $name;
    const HORN = false;
    public function getName()
    {
        return $this->name;
    }
    public function checkHorn()
    {
        return self::HORN;
    }
}
?>

Use Interface

➔ Create interface

➔ Create interface inheritance interface

<?php
interface Animal
{
    public function getName();
}

interface Buffalo extends Animal
{
    public function checkHorn();
}

public class TheCalf implements Buffalo
{
    private $name;
    const HORN = false;
    public function getName()
    {
        return $this->name;
    }
    public function checkHorn()
    {
        return self::HORN;
    }
}
?>

All rights reserved

Viblo
Hãy đăng ký một tài khoản Viblo để nhận được nhiều bài viết thú vị hơn.
Đăng kí