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?