加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > PHP教程 > 正文

php – 强迫某人使他的子类实现接口的方法

发布时间:2020-12-13 17:42:09 所属栏目:PHP教程 来源:网络整理
导读:我想知道如何强制子类来实现给定的接口方法. 假设我有以下课程: interface Serializable{ public function __toString();}abstract class Tag // Any HTML or XML tag or whatever like div,p,chucknorris,etc{ protected $attributes = array(); public fu
我想知道如何强制子类来实现给定的接口方法.

假设我有以下课程:

interface Serializable
{
    public function __toString();
}

abstract class Tag // Any HTML or XML tag or whatever like <div>,<p>,<chucknorris>,etc
{
    protected $attributes = array();

    public function __get($memberName)
    {
        return $this->attributes[$member];
    }

    public function __set($memberName,$value)
    {
        $this->attributes[$memberName] = $value;
    }

    public function __construct() { }

    public function __destruct() { }
}

我想强制任何子类“Tag”来实现“Serializable”接口.例如,如果我是一个“Paragraph”类,它会看起来像这样:

class Paragraph extends Tag implements View
{
    public function __toString()
    {
        print '<p';
        foreach($this->attributes as $attribute => $value)
            print ' '.$attribute.'="'.$value.'"';
        print '>';

        // Displaying children if any (not handled in this code sample).

        print '</p>';
    }
}

我如何强迫开发人员使他的“Paragraph”类从“Serializable”接口实现方法?

感谢您抽出宝贵时间阅读.

解决方法

只需要抽象类实现接口:

interface RequiredInterface 
{
    public function getName();
}

abstract class BaseClass implements RequiredInterface 
{

}

class MyClass extends BaseClass
{

}

运行此代码将导致错误:

Fatal error: Class MyClass contains 1 abstract method and must
therefore be declared abstract or implement the remaining methods
(RequiredInterface::getName)

这要求开发人员编写RequiredInterface的方法.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读