简体   繁体   English

疯狂混乱PHP OOP同时“实现”“扩展”

[英]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? 你能帮我解释一下它如何“ implements ”“ extends ”吗?
Does it just combine the 3 class together? 它只是将3级组合在一起吗?

I am totally confused! 我完全糊涂了!

extends is for inheritance, ie inheriting the methods/fields from the class. extends用于继承,即继承类中的方法/字段。 A PHP class can only inherit from one class. PHP类只能从一个类继承。

implements is for implementing interfaces. implements用于实现接口。 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). 此代码在第5行引发致命错误,因为接口上的方法未正确实现(参数缺失)。 It would also throw a fatal error in line 6 as the method from the interface is not implemented at all. 它也会在第6行引发致命错误,因为接口上的方法根本没有实现。

Yes, PHP can implement multiple interface using implements , but it can inherit only one class using extends 是的,PHP可以使用implements实现多个接口,但它只能使用extends继承一个类

Implements and extends are two different kinds of shoes. 实施和扩展是两种不同的鞋子。

Extends tells the compiler/interpreter that the class is derived from an other class. Extends告诉编译器/解释器该类是从另一个类派生的。 Implements tells the compiler/interpreter, that the class must implement a contract, defined in an interface. Implements告诉编译器/解释器,该类必须实现在接口中定义的契约。

Look up interfaces, as they are the backbone of polymorphy in OOP. 查找接口,因为它们是OOP中多态的支柱。 Extends basically implements the public (and semi public, protected) interface of the super class automatically, as you derive from it. 当你从中派生时,Extends基本上实现了超类的公共(和半公共,受保护)接口。

extends : can use and/or override any parent's method. extends :可以使用和/或覆盖任何父方法。

implements : must have all the interface methods: every interface's method must be at least declared in the class that implements. implements :必须具有所有接口方法:每个接口的方法必须至少在实现的类中声明。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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