其中一个主要的设计原则是接口的程序而不是实现.这在PHP或任何其他弱类型语言中甚至是可能的.
编辑:
我也许没有像我应该的那样清楚地写出这个问题.我不是说php不能使用接口 - 它显然可以.我的意思是设计原则"接口而不是实现的程序"在弱类型语言中变得多余.
是的。定义接口:
interface iTemplate
{
public function setVariable($name, $var);
public function getHtml($template);
}
Run Code Online (Sandbox Code Playgroud)
并实施它:
// Implement the interface
class Template implements iTemplate
{
private $vars = array();
public function setVariable($name, $var)
{
$this->vars[$name] = $var;
}
public function getHtml($template)
{
foreach($this->vars as $name => $value) {
$template = str_replace('{' . $name . '}', $value, $template);
}
return $template;
}
}
Run Code Online (Sandbox Code Playgroud)
PHP 接口手册:http://php.net/manual/en/language.oop5.interfaces.php
我不知道为什么仅仅因为语言是弱类型就不可能有接口。
编辑:拥有接口的目的(或多或少)是这样你就可以重复使用你的代码,而不管实际实现所述接口的类是什么。
假设您的程序使用一个接口,该接口Set具有方法addItem()和removeItem()。contains()通过接口,您知道您将能够调用这 3 种方法中的任何一种,而不管底层Set实现如何,无论是 HashSet、TreeSet 还是其他。
如果您使用弱类型语言,这一点不会改变;您仍然可以像使用强类型语言一样进行编码。我知道我的解释不太好,但我希望你能明白。