Object-Oriented Programming Simple Doubt with Implements

Asked

Viewed 36 times

2

I’m using a php library.

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

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

  • 1

    you have no class that implements this interface?

  • @rray has this comment in the //Rich text element interface library. and It has a rich text class, but I do not see in it the implementation of this interface.

  • If she implemented, just call the normal methods?

  • 1

    The idea is exactly the same, the only detail is that the class you need to instantiate needs to be an implementation of this interface. Which class would that be depends on the context, what you’re doing and which library it is.

  • If you implement, just pass this object as an argument and you can call the methods normally. Note that the interface forces you to implement some methods. Setting the parameter type as an interface allows you to make 'input' more flexible'.

  • @Andersoncarloswoss library is PHPOFFICE - Phppresentation

Show 1 more comment

1 answer

3


Well, in this case this signature is obliging the value passed to implement the interface Textelementinterface. The example below is very simple, but I believe it is suitable 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 parameter new ImplementaInterface('Qualquer coisa aqui'), this class is implemented the ** Textelementinterface interface**.

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

  • 1

    Cool! helped me, I managed to implement here and it worked!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.