Problems passing object instantiated by function parameter with php

1

I have a php file that instantiates a class, but I'm not able to pass this object instantiated as a parameter to another class. Example.

$usuario = new Usuario();
$email = new Email();
$email->send($usuario);

In the Email class I can not use the getters and setters of the user class.

class Email {
    function($usuario) {
        mail($usuario->getId());
    }
}
    
asked by anonymous 21.07.2017 / 21:20

2 answers

1

The problem you are having is Injection of Dependency .

The dependency of a class occurs when you "inject", passing one class to be worked within the other.

  

This means that in order for there to be a dependency injection, the instantiation of an object should not occur within the class, but outside the class and then injected.

One of the ways to accomplish this is to inject the external class through the constructor method .

Let's go to the example:

<?php

class Email  
{
    public function send()
    {
        // TODO
    }
}

class Usuario  
{
    protected $email;

    //Injeção de dependência através do método construtor
    public function __construct(Email $email)
    {
        $this->email = $email;
    }

    public function porEmail()
    {
        $this->email->send();
    }
}
  

__ construct () is how you declare a constructor method in PHP, unlike languages like Java where you use the same class name, for example: public User ().

Note that now when calling method $command->porEmail() we are actually triggering the send() method of class $email , for example, we can do this:

$email = new email();

$anunciar = new Usuario($email);
$anunciar->porEmail();

Note that the Usuario class receives by injection $email . This whole process we have done means dependency injection. See how simple?

    
21.07.2017 / 22:46
0

In the email class in your send method before the parameter specifies the obj q will pass type

public function send(Usuario $usuario){
// seu codigo
}

I hope this is what you are looking for

    
21.07.2017 / 21:33