简体   繁体   中英

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 ?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM