0

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 ?

6
  • 1
    In constructor you inject 10 instead of User object. Commented Feb 15, 2015 at 9:45
  • 1
    The constructor of Article requires a user, not an integer; instead, you should do this: $news = new Article(new User(10)); echo $news->getAuthorName(); Commented Feb 15, 2015 at 9:45
  • What means: WSOD ? Also $news = new Article(10); -> $news = new Article(new User(10)); Commented Feb 15, 2015 at 9:45
  • @Rizier123 WSOD stands for White Screen Of Death Commented Feb 15, 2015 at 9:45
  • WSOD means White Screen of Death Commented Feb 15, 2015 at 9:45

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.