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

我想知道如何强制子类来实现给定的接口方法.

假设我有以下课程:

interface Serializable

{

public function __toString();

}

abstract class Tag // Any HTML or XML tag or whatever like

,

, , 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 '

foreach($this->attributes as $attribute => $value)

print ' '.$attribute.'="'.$value.'"';

print '>';

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

print '

';

}

}

我如何强迫开发人员使他的“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的方法.

标签:php,interface,subclass

来源: https://codeday.me/bug/20190613/1232487.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值