The problem you’re having is Dependency injection .
The dependency of one class occurs when "injected", passes one class to be worked within the other.
This means that in order to have an injection of dependency, the instantiation of an object must not take place within the class, but outside it and then injected.
One of the ways to accomplish this is by injecting the external class through the construction method.
Let’s take a look at 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 to declare a constructor method in PHP, different from languages like Java where the same class name is used, for example: public Usuario().
Note that now when calling the method $command->porEmail()
we’re actually triggering the method send()
class $email
, for example, we can do so:
$email = new email();
$anunciar = new Usuario($email);
$anunciar->porEmail();
Note that the class Usuario
receives by addiction injection $email
. This whole process that we’ve done means dependency injection. You see how simple it is?
Enter the code of
Email::send
also– bfavaretto
Ready, I put.
– Krint
But the function has no name?
function($usuario) {
– rray
Whoa, I forgot to put it on, it’s called send.
– Krint
mail()
is that default php function?$usuario->getId()
returns some error?– rray
Well, in vdd this is just an example. My code is much more complex than that. But even if I put
return $usuario->getId()
it doesn’t work– Krint
@Krint then edit the question and correct. Put at least this method in full.
– Woss