Thursday, 9 February 2012

PHP 5 OOP Interface Sample/Example

<?PHP

/*
In PHP 5, interfaces may declare only methods. An interface cannot declare any variables. To extend from an Interface, keyword implements is used. PHP5 supports class extending more than one interface.
Interfaces is also an abstract class because abstract class always require an implementation. In PHP 5 class may inherit only one class, but because interfaces lack an implementation any number of class can be inherited.



PRIMARY PURPOSES OF AN INTERFACE:

    Interfaces allow you to define/create a common structure for your classes – to set a standard for objects.
    Interfaces solves the problem of single inheritance – they allow you to inject ‘qualities’ from multiple sources.
    Interfaces provide a flexible base/root structure that you don’t get with classes.
    Interfaces are great when you have multiple coders working on a project – you can set up a loose structure for programmers to follow and let them worry about the details.

WHEN SHOULD YOU MAKE A CLASS AND WHEN SHOULD YOU MAKE AN INTEFACE?

    If you have a class that is never directly instantiated in your program, this is a good candidate for an interface. In other words, if you are creating a class to only serve as the parent to other classes, it should probably be made into an interface.
    When you know what methods a class should have but you are not sure what the details will be.
    When you want to quickly map out the basic structures of your classes to serve as a template for others to follow – keeps the code-base predictable and consistent.


*/

interface employee
{
    function setdata($empname,$empage);
    function outputData();
}

class Payment implements employee
{
    function setdata($empname,$empage)
    {
            //Functionality
    }

    function outputData()
    {
        echo "Inside Payment Class";
    }
}

class Credit extends Payment implements employee
{
    function setdata($empname,$empage)
    {
            //Functionality
    }

    function outputData()
    {
        echo "Inside Credit Class";
    }
}

class Debit extends Credit implements employee
{
    function setdata($empname,$empage)
    {
            //Functionality
    }

    /*function outputData()
    {
        echo "Inside Credit Class";
    }*/
}

$a = new Debit();
$a->outputData();
?>

No comments:

Post a Comment