-
Notifications
You must be signed in to change notification settings - Fork 15
Expand file tree
/
Copy pathdependency-injection.php
More file actions
executable file
·57 lines (47 loc) · 1.27 KB
/
dependency-injection.php
File metadata and controls
executable file
·57 lines (47 loc) · 1.27 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
<?php
// Dependency Injection example
// Now you don't need to use inheritance when you need to use more than one class.
class Author // Normal class
{
private $firstName;
private $lastName;
public function __construct($firstName, $lastName)
{
$this->firstName = $firstName;
$this->lastName = $lastName;
}
public function getFirstName()
{
return $this->firstName;
}
public function getLastName()
{
return $this->lastName;
}
}
// Class using DI in the constructor
// Inserting the Author class as an argument
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;
}
}
// Both Question and Author Class methods can be accessed through the $question instances
// prints: John Doe. Is this dependency injection?
$question = new Question('. Is this dependency injection?', new Author('John ', 'Doe'));
echo $question->getAuthor()->getFirstName();
echo $question->getAuthor()->getLastName();
echo $question->getQuestion();