PHP依赖注入

时间:2015-03-05 02:39:34

标签: php dependency-injection

我正在尝试理解有关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('John', 'Doe');
$qn = new Question('What is your name?', $author);
$authorName = $qn->getAuthor();
print_r($authorName);

返回以下内容: -

Author Object
(
    [firstName:Author:private] => John
    [lastName:Author:private] => Doe
)

如何访问Author对象的值,即。 firstName和lastName?

我尝试 $ authorName-> firstName ,但这会让我返回错误

Cannot access private property Author::$firstName

就像我说的那样,我只是试图通过使用此代码示例来获取依赖注入。我知道通过在Author类中将类型$ firstName更改为public将使其工作,但如果代码示例不正确或我的代码检索值不正确,仍需要任何PHP专家的说明。

感谢并非常感谢任何反馈。

2 个答案:

答案 0 :(得分:0)

这里的范例是每个"私人"字段中有相应的" public"获得该领域的功能。这就是你从$ qn对象中获取作者的方式:通过同样地调用$qn->getAuthor(),因为这会给你一个作者并且你想要作者的名字,你会使用

$author = $qn->getAuthor();
$firstname = $author->getFirstName();

依赖注入只是强制要求当你提出问题时,传递给构造函数的第二个参数必须是Author类型

答案 1 :(得分:0)

如果要从Question类访问作者姓名,可以修改getAuthor函数:

班级问题 getAuthor()

public function getAuthor() {
    // call the author class then call the method you want to retreive
    // call the author info by using any proterties inside the 
    //author class ex. $this->author->getFirstName()
    return $this->author->getFirstName().' '.$this->author->getLastName();
}

致电

$authorName = $qn->getAuthor();
print_r($authorName);
// you will get John Doe