基本的PHP面向对象实例化和依赖注入

时间:2013-12-11 17:27:29

标签: php

我正在尝试学习使用依赖注入,但是在使用它时遇到了问题。我理解这里的两个课程正在发生什么,但是当我去使用它们时,我做错了什么。

class Author
{
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 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;
}
}

好的,有两个基本类使用依赖注入。我理解所有这些,但如果我想使用它们。我试过这个,但是我收到了一个错误。

$author = new Author('Mickey', 'Mouse');
$author->getFirstName();

$question = new Question('what day is it?', $author);
$question->getQuestion(); 

我希望它输出'Mickey'和'它是什么日子?',但我得到以下错误。

Undefined variable: firstName in /var/www/OOP/dependency-injection/example1.php on line 12
Undefined variable: lastName in /var/www/OOP/dependency-injection/example1.php on line 13

为什么我收到此错误?我以为我在这里声明了变量$author = new Author('Mickey', 'Mouse');

感谢您的任何见解。

2 个答案:

答案 0 :(得分:4)

您的firstnamefirstNameAuthor班级不匹配

public function __construct($firstname, $lastname)
{
    $this->firstName = $firstName;
    $this->lastName = $lastName;
}

应该是

private $firstName;
private $lastName;
public function __construct($firstName, $lastName)
    {
        $this->firstName = $firstName;
        $this->lastName = $lastName;
    }

答案 1 :(得分:1)

您已声明private $firstname,并且在getter中调用$this->firstName大写。