How important is the interface in this particular code?

2

If we put the functions of the interface, also inside the class, so we can create interface?

Example:

Interface

interface Teste {
    function olaMundo($texto);
}

Class

class Testando implements Teste {
    function olaMundo($texto); //Método da interface
}

Index.php

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title>Teste</title>
    </head>
    <body>
        <?php
            require_once 'Testando.php';
            $i = new Testando;
            $i->olaMundo("Ola mundo!");
        ?>
    </body>
</html>

Then, what was the role of the interface in this code?

    
asked by anonymous 10.07.2017 / 18:37

1 answer

7

In this specific example it appears to have no role at all. Too abstract examples do not usually teach the use of something, except for rare cases. The example may be fictional, but when you look at whether the concept is being followed you can not simply put any nonsense. Do not just put a set of words. In context programming is very important. The detail is what defines what to do. Significant names are documentation and can explain what is happening there. This code says nothing unless it's a test, it does not give context.

This is a case where the interface is not having utility because it was put to illustrate something meaningless. Interfaces are useful for abstracting ideas, to establish contracts when necessary. This case is not necessary.

If it were a real case, it would have one or more method signatures that would serve as a contract, so the type interface could be used somewhere and every class that implements the interface could be used in a given algorithm. What is very strange in a language that preaches dynamic typing, but we already know it is PHP.

If you do not have an advantage a specific function does not use. This goes for anything. Usefulness is in complex systems, where contracts have to be respected.

Some interface questions available on the site that should help understand:

10.07.2017 / 18:45