Doubt about the syntax of dependency injection

1

Starting, for example, from this class

class Question 
{ 
    private $author; 
    private $question; 

    public function __construct($question, Author $author) 
    { 
        $this->author = $author; 
        $this->question = $question; 
    } 

    public function getAuthor() 
    { 
        return $this->author; 
    } 

    public function getQuestion() 
    { 
        return $this->question; 
    } 
}

In the parameters of the constructor we have the classic syntax (my doubt is about that syntax) of the injection of dependencies (Author $ author), first the namespace of the class in question and then a variable, but for more than I have I tried to document on the subject I do not find a clear answer, I do not know exactly (I guess but I do not know for sure) what this syntax is like.

I guess you pass the class (Author) to the variable ($ author) so that this variable has a full instance of the class. Is that so? I would like you to illustrate me with some example, maybe it's crazy, but would it be the same (or would it be something similar) to do something like that?

public function __construct($question, new Author $author) 
{ 
    $this->author = $author; 
    $this->question = $question; 
} 

The general question would be that, when passing the namespace as an argument and next to the variable Would that variable have a complete instance of the namespace class?

    
asked by KurodoAkabane 27.09.2017 в 13:29
source

1 answer

2

The only thing you are doing with public function __construct($question, Author $author) is "TYPE" the argument, that is, you are telling the Question class that it can only accept instances of the Author class as a second argument.

The injection of dependencies means that you are passing the necessary instance for the operation of your class instead of instantiating it directly in the method.

Normally, it will be a "container" that instans the dependency and passes it to the new class.

The code public function __construct($question, new Author $author) is not valid and will cause an error.

    
answered by 27.09.2017 / 14:34
source