开发者

Usage of Interfaces

开发者 https://www.devze.com 2023-01-12 14:11 出处:网络
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.

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?

Exampl开发者_运维百科e:

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?


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() {}
}


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...


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消