tags:

views:

54

answers:

3

Just a clarification from an earlier question about OO PHP. I've checked on the php.net website but still not completely sure. Should be a quick answer, I expect.

When 'defining' methods in an interface, must the class that implements it use all the listed methods from the interface?

Example:

interface foo {
    public function blah();
    public function de();
    public function bleh();
}

class bar implements foo {
    public function blah() {
        //Code here
    }

    public function bleh() {
        //More code here
    }
}

Would that work?

+1  A: 

No. A class implementing an interface must implement all methods defined by the interface or be defined abstract. If you try to run the script without all methods defined you'll get

Fatal error: Class bar contains 1 abstract method and must therefore be declared abstract or implement the remaining methods

In other words, either do

abstract class bar implements foo {}

or

abstract class bar implements foo {
        public function blah() { /* code */ }
        public function bleh() { /* code */ }    
}

or leave some methods empty in the concrete class

class bar implements foo {
    public function blah() { /* code */ }
    public function bleh() { /* code */ }
    public function de() {}
}
Gordon
Thanks Gordon. That really cleared it up for me.
Saladin Akara
+1  A: 

Well, yes and no. You can implement a subset of the interface in an abstract class. Note that you can't instantiate abstract classes (but it's useful for providing common functionality).

For instantiated classes, they must always implement the entire interface. That's the point of the interfaces, that you know that if $foo instanceof foointerface it'll always support every aspect declared in the interface (and hence not error or do something unexpected when you do $bar->de()...

The docs on interfaces are actually fairly good. I'd recommend giving it a read...

ircmaxell
A: 

no, it won't work. when you try to instantiate the class you will get an error. the whole point of interfaces is to defined functions that MUST be defined in an instanciatet object that implenents the interface. what you CAN do however is to extend another class to the class you already defined, define the missing function there and instanciate this one.

Joe Hopfgartner