我想知道如何强制子类来实现给定的接口方法.
假设我有以下课程:
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