我很难理解给定的代码和依赖注入背后的原因。我收到了以下错误:
未捕获错误:调用未定义的方法问题:: getFullName()在C:\ xampp \ htdocs \ OOP \ Index.php:10堆栈跟踪:#0 {main}抛出C:\ xampp \ htdocs \ OOP \第10行的Index.php。
即使我在构造函数中实例化Author
类的对象,在尝试使用Question
后,我仍会在getQuestion()
类中获取字符串。
require 'Author.php';
class Question {
private $author;
private $question;
public function __construct($question, Author $author) {
$this->author = $author;
$this->question = $question;
}
public function getAuthor() {
$firstname = $this->author->getFirstName();
$lastname = $this->author->getLastName();
$fullaname = $firstname . $lastname;
return $this;
}
public function getQuestion() {
return $this->question;
}
}
<?php
class Author {
private $firstName;
private $lastName;
private $fullName;
public function __construct($firstName, $lastName) {
$this->firstName = $firstName;
$this->lastName = $lastName;
}
public function getFirstName() {
return $this->firstName;
}
public function getLastName() {
return $this->lastName;
}
public function getFullName() {
return $this->fullName = $this->firstName." ".$this->lastName;
}
}
require 'Question.php';
$question = new Question("What is the author's name?", new Author("josel", "parayno"));
echo $question->getQuestion();
echo $question->getFullName();
答案 0 :(得分:2)
$ question确实没有getFullName方法。方法getFullName存在于类Author中。在创建和&#34;发送&#34; to Question,当它被创建时,方法getFullName在类Question private $ author property。
中可用但如果您想通过以下代码获取Athor名称,则需要尝试
$question->getAuthor()->getFullName();
如果你这样做,你再次犯错,因为问题 - > gt; getAuthor你返回$ this,在这种情况下这是一个Question对象。要从问题对象中获取作者姓名,您应该遵循:
public function getAuthor() { $firstname = $this->author->getFirstName(); $lastname = $this->author->getLastName(); return $this->author; }
echo $ question-&gt; getAuthor() - &gt; getFullName();