Program to an interface not an implementation in php
One of the major design principles is program to an interface not an implementation. Is this even possible in php or any other weakly typed language.
EDIT:
I maybe didnt write the question as clearly as i should have. I dont mean that php cant use interfaces - it obvisouly can. I mean does the design principle "program to an interface and not an implementation" become redundant in weakly typed languages.
Yes. Define the interface:
interface iTemplate
{
public function setVariable($name, $var);
public function getHtml($template);
}
And implement it:
// 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;
}
}
PHP manual on Interfaces: http://php.net/manual/en/language.oop5.interfaces.php
I don't know why it wouldn't be possible to have interfaces just because the language is weakly typed.
EDIT: The point (more or less) of having an interface is so you can re-use your code regardless of the class that actually implements said interface.
Say your program uses an interface Set
, which has methods addItem()
, removeItem()
and contains()
. With interfaces, you know you'll be able to call any of these 3 methods regardless of the underlying Set
implementation, be it HashSet, TreeSet or whatever.
This doesn't change if you are using a weakly typed language; you can still code as if you were using a strongly typed language. I know I didn't word this explanation really well, but I hope you get the idea.
php has interfaces and you can program to them. Why shouldn't you be able to do that?
Programming to an interface means that you just use the functionality that is offered by the interface and neither rely on implementation details nor use other functionality that is offered by the implementation and you just happen to know about it, because the implementation might change (the interface shouldn't).
Depends on what you mean by "interface" and "implementation". These are loose terms whose meanings can shift depending on context.
PHP5 contains OOP constructs similar to Java and C#, such as Objects as references, Classes, Abstract classes and Interfaces. It also contains type hinting for method paramaters. These tools could be, and have been, used to build "an interface" for something.
链接地址: http://www.djcxy.com/p/47230.html上一篇: 磁盘数据库存储,最佳实践
下一篇: 编程到一个接口,而不是在PHP中的实现