Object-Oriented Programming Simple Doubt with Implements

2

I'm using a php library.

It has a class with a method that takes as parameter exactly this text that I will write: TextElementInterface $pText = null . In the definition of TextElementInterface it is an interface.

How do I pass this via parameter? for example if it was a class it was just instantiate to assign it to a variable and pass that variable by parameter in the desired method, but an interface I do not know how to do?

    
asked by anonymous 18.10.2017 / 15:15

1 answer

3

Well, in this case this signature is forcing the last value to implement the TextElementInterface interface. The example below is very simple, but I believe it is appropriate for the question:

<?php

interface TextElementInterface
{
    public function __construct($pText);
}

class ImplementaInterface implements TextElementInterface
{
    public function __construct($pText) {
        return $pText;
    }
}

class MinhaClasse
{
    public function chamarMetodo(TextElementInterface $pText = null) {
        echo "Opa! Funciona.";
    }
}

$obj = new MinhaClasse;
$obj->chamarMetodo(new ImplementaInterface('Qualquer coisa aqui'));

Note that I passed as new ImplementaInterface('Qualquer coisa aqui') parameter, this class is implemented in the interface ** TextElementInterface **.

If you try something like: $obj->chamarMetodo('Qualquer coisa aqui'); you will see that an error occurs because the interface is not being implemented.

    
18.10.2017 / 15:33