我試圖學習使用依賴注入,但是在使用時遇到問題。我明白這裏兩個班的情況,但是當我去使用他們時,我做錯了什麼。基本的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();
我希望它輸出「米奇」和「今天是哪天?」,但我得到以下錯誤。
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');
?
感謝您的任何見解。
獲取代碼完成的IDE,並牢記PHP區分大小寫。選擇一種像camelCase的樣式,並堅持下去;) – Jessica
這個問題似乎是脫離主題,因爲它是關於debbuging代碼,並且將來沒有價值的訪問者。 –