Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Program to an interface not an implementation in php

Tags:

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.

like image 281
David Avatar asked Aug 01 '10 20:08

David


1 Answers

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.

like image 79
NullUserException Avatar answered Oct 03 '22 18:10

NullUserException