gpt4 book ai didi

php - 编程到接口(interface)而不是 php 中的实现

转载 作者:可可西里 更新时间:2023-11-01 12:57:14 25 4
gpt4 key购买 nike

主要设计原则之一是针对接口(interface)而不是实现进行编程。这在 php 或任何其他弱类型语言中甚至可能吗?

编辑:

我可能没有把问题写得像我应该的那样清楚。我并不是说 php 不能使用接口(interface)——它显然可以。我的意思是“针对接口(interface)而非实现编程”的设计原则在弱类型语言中是否变得多余。

最佳答案

是的。定义接口(interface):

interface iTemplate
{
public function setVariable($name, $var);
public function getHtml($template);
}

并实现它:

// 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;
}
}

关于接口(interface)的 PHP 手册:http://php.net/manual/en/language.oop5.interfaces.php

我不知道为什么仅仅因为语言是弱类型就不可能有接口(interface)。


编辑:拥有接口(interface)的要点(或多或少)是让您可以重用您的代码,而不管实际实现所述接口(interface)的类是什么。

假设您的程序使用接口(interface) Set,它有方法 addItem()removeItem()contains()。通过接口(interface),您知道您将能够调用这 3 种方法中的任何一种,而不管底层的 Set 实现是什么,无论是 HashSet、TreeSet 还是其他。

如果您使用的是弱类型语言,这不会改变;您仍然可以像使用强类型语言一样编写代码。我知道我没有很好地解释这个解释,但我希望你明白了。

关于php - 编程到接口(interface)而不是 php 中的实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3383605/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com