简体   繁体   中英

Crazy Confusing PHP OOP “implements” “extends” at the same time

abstract class SF_Model_Acl_Abstract 
    extends SF_Model_Abstract
    implements SF_Model_Acl_Interface, Zend_Acl_Resource_Interface
{
    protected $_acl;
    protected $_identity;
    public function setIdentity($identity)
    {
    if (is_array($identity)) {
        ......
        ......

Can you help me explain how it can " implements " " extends " at the same time?
Does it just combine the 3 class together?

I am totally confused!

extends is for inheritance, ie inheriting the methods/fields from the class. A PHP class can only inherit from one class.

implements is for implementing interfaces. It simply requires the class to have the methods which are defined in the implemented interfaces.

Example:

interface INamed { function getName($firstName); }
class NameGetter { public function getName($firstName) {} }
class Named implements INamed { function getName($firstName) {} }
class AlsoNamed extends NameGetter implements INamed {}
class IncorrectlyNamed implements INamed { function getName() {} }
class AlsoIncorrectlyNamed implements INamed { function setName($newName) {} }

This code throws a fatal error in line 5 as a method from the interface is not properly implemented (argument missing). It would also throw a fatal error in line 6 as the method from the interface is not implemented at all.

Yes, PHP can implement multiple interface using implements , but it can inherit only one class using extends

Implements and extends are two different kinds of shoes.

Extends tells the compiler/interpreter that the class is derived from an other class. Implements tells the compiler/interpreter, that the class must implement a contract, defined in an interface.

Look up interfaces, as they are the backbone of polymorphy in OOP. Extends basically implements the public (and semi public, protected) interface of the super class automatically, as you derive from it.

extends : can use and/or override any parent's method.

implements : must have all the interface methods: every interface's method must be at least declared in the class that implements.

它只是实现接口,它描述了所需的方法,因此其他方法有一个定义的接口可以使用,请参阅http://php.net/manual/en/language.oop5.interfaces.php

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM