call injected object's method

I'm learning about dependency injection in php and I think there's something I'm missing.

I created two classes, Author and 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;
    }
}

Then, on my index page, I instantiated my Article class and injected my Author class:

require "Classes.php";
$Article = new Article( new Author("Chris", "Schmitz"), "this is the content of my article");

print_r($Article);

Which prints out my object as expected:

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 ) 

This all makes sense, but when I go to call the public method getName() from my Author class I get an error:

echo $Article->author->getName();
// produces php error: PHP Fatal error:  Cannot access private property Article::$author

If I'm injecting one object into the other, shouldn't I be able to access the injected object's public methods? Am I misunderstanding how the injection is expected to work? Did I set it up wrong?


$author is a private property of Article , meaning you can only access it from methods inside that class.

Although the getName() method is indeed public , all parts of the -> chain have to be visible from the context in which you're using them - unfortunately author isn't.

As suggested by Halim, the cleanest way to address the error is to create a public getter method for the author property in your Article class:

public function getAuthor() {
    return $this->author;
}
链接地址: http://www.djcxy.com/p/82280.html

上一篇: PHP依赖注入并从伞班延伸

下一篇: 调用注入对象的方法