Reputation: 1434
Ey guys, I am trying to learn Dependency Injection and I wrote this code:
class User {
public $id;
public function __construct($id) {
$this->id = $id;
}
public function getName() {
return 'Alex';
}
}
class Article {
public $author;
public function __construct(User $author) {
$this->author = $author;
}
public function getAuthorName() {
return $this->author->getName();
}
}
$news = new Article(10);
echo $news->getAuthorName();
However, I am getting WSOD. What had I done wrong in it ?
Upvotes: 0
Views: 61
Reputation: 4275
You have specified wrong instance.Use the code below
<?php
class User {
public $id;
public function __construct($id) {
$this->id = $id;
}
public function getName() {
return 'Alex';
}
}
class Article {
public $author;
public function __construct(User $author) {
$this->author = $author;
}
public function getAuthorName() {
return $this->author->getName();
}
}
$news = new Article(new User(10));
echo $news->getAuthorName(); //Outputs Alex
Hope this helps you
Upvotes: 1