nicolas
nicolas

Reputation: 101

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!

Upvotes: 10

Views: 15001

Answers (5)

T30
T30

Reputation: 12242

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.

Upvotes: 2

Falcon
Falcon

Reputation: 3180

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.

Upvotes: 5

ThiefMaster
ThiefMaster

Reputation: 318798

extends is for inheritance, i.e. 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.

Upvotes: 17

konsolenfreddy
konsolenfreddy

Reputation: 9671

It just implements interfaces, which describe which methods are required, so other methods have a defined interface to work against, see http://php.net/manual/en/language.oop5.interfaces.php

Upvotes: 1

EGL 2-101
EGL 2-101

Reputation: 1265

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

Upvotes: 5

Related Questions