bthe0
bthe0

Reputation: 1434

PHP Dependency Injection issue

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

Answers (1)

Utkarsh Dixit
Utkarsh Dixit

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

Related Questions