Why we use Interfaces in OOP?

Discussion in 'PHP' started by mindblaster, May 12, 2011.

  1. #1
    I am the student of OOP and PHP and i am creating a website in PHP, and i read about the interfaces but i have no idea why actually i use them. can any one tell me. in interface we only define the method signature not the definition of method so why use interfaces we can do this also in class. Please help me to clear my ideas about interfaces
     
    mindblaster, May 12, 2011 IP
  2. littlejohn199

    littlejohn199 Peon

    Messages:
    42
    Likes Received:
    3
    Best Answers:
    0
    Trophy Points:
    0
    #2
    littlejohn199, May 12, 2011 IP
  3. JoelLarson

    JoelLarson Peon

    Messages:
    61
    Likes Received:
    2
    Best Answers:
    0
    Trophy Points:
    0
    #3
    In PHP, an interface can be thought of as a "blueprint" for a class that extends it. A practical solution for an interface would be a script that allows mod extensions. Say that for every mod that extends the script, it must have an install(), uninstall(), and execute() command. Defining it as an interface will prevent classes from not having all the basic methods needed (like a blueprint). It also helps remind developers of their own code when they haven't worked on it for a long period of time.

    <?php
    
    interface Module
    {
    public function install($params, $directory);
    public function execute($priority);
    public function uninstall();
    }
    PHP:
    It's similar to an abstract PHP class, but an interface isn't allowed to define the contents of a function or variable.
     
    JoelLarson, May 13, 2011 IP
  4. joebert

    joebert Well-Known Member

    Messages:
    2,150
    Likes Received:
    88
    Best Answers:
    0
    Trophy Points:
    145
    #4
    An interface is more or less an easy way to keep a list of functions/methods in an easy to read format for developers, documentation writers, and anyone else who might not want to look through the entire code base to get a list of capabilities.
     
    joebert, May 14, 2011 IP
  5. mofta7y

    mofta7y Member

    Messages:
    29
    Likes Received:
    1
    Best Answers:
    0
    Trophy Points:
    38
    #5
    if you are programming you php app alone and dont want it to be extendable you will never use interfaces

    interfaces in practice are used in 2 situation

    1- extendability : you want the users to add new functions to software you released as source code and you want them to do it write so they have to implement the interface and by that will be forced to implement all its methods

    2- working with your team mates : you create interfaces to make sure that if someone of your teammates continue working on something you started he/she will have a guide to what to implement and what to do
     
    mofta7y, May 15, 2011 IP