我正在学习php中的依赖注入,我认为我缺少一些东西。
我创建了两个类,Author和Article
class Author{
private $firstName;
private $lastName;
public function __construct($firstName, $lastName){
$this->firstName = $firstName;
$this->lastName = $lastName;
}
public function getName(){
return $this->firstName . " " . $this->lastName;
}
}
class Article{
private $author;
private $content;
public function __construct(Author $author, $content){
$this->author = $author;
$this->content = $content;
}
public function getContent(){
return $this->content;
}
}然后,在我的索引页面上,实例化了我的文章类并注入了我的Author类:
require "Classes.php";
$Article = new Article( new Author("Chris", "Schmitz"), "this is the content of my article");
print_r($Article);它按预期打印出我的对象:
Article Object ( [author:Article:private] => Author Object ( [firstName:Author:private] => Chris [lastName:Author:private] => Schmitz ) [content:Article:private] => this is the content of my article ) 这一切都是有意义的,但是当我从我的getName()类调用公共方法Author时,我会得到一个错误:
echo $Article->author->getName();
// produces php error: PHP Fatal error: Cannot access private property Article::$author如果我将一个对象注入另一个对象,难道不能访问注入对象的公共方法吗?我是否误解了注射是如何工作的?我搞错了吗?
发布于 2014-01-18 20:05:49
$author是Article的一个private属性,意味着您只能从该类中的方法访问它。
尽管getName()方法确实是public,但->链的所有部分都必须从使用它们的上下文中可见--不幸的是,author不能。
正如Halim所建议的,解决错误的最干净方法是为您的public类中的author属性创建一个Article getter方法:
public function getAuthor() {
return $this->author;
}https://stackoverflow.com/questions/21209185
复制相似问题