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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With