Interfaces

Last updated

What is Interfaces?

Interfaces in PHP serve as a blueprint for designing classes. They ensure that a class adheres to a certain contract, all without defining how those methods should function. As PHP is not a strictly typed language, interfaces can be particularly useful in large codebases to maintain continuity and predictability. For example, in PHP, an interface 'iTemplate' could be defined with methods 'setVariable' and 'getHtml'. Any class that implements this interface must define these methods.

Here is a snippet:

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

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

Free resources to learn Interfaces

More in stage 12: PHP-FIG

Interfaces: common questions

Can I learn Interfaces in Hindi?

This lesson is written in English. Once you sign in, open it in the interactive course and ask the AI tutor to explain Interfaces in Hindi or Hinglish. The tutor answers from this lesson’s own text, so it stays on the syllabus, and it runs on your own Google, OpenAI or Anthropic key.

Is this Interfaces tutorial for beginners?

It is lesson 85 of 120 in the free PHP roadmap, in stage 12, PHP-FIG. If you are new to PHP, start from stage 1 and come back here in order; if you already know the earlier stages, this lesson stands on its own.

Still confused? Ask me