php - Passing class from another class or dependency injection -
i'm having difficulties understand given code , reason behind dependency injection. i've got following error:
uncaught error: call undefined method question::getfullname() in c:\xampp\htdocs\oop\index.php:10 stack trace: #0 {main} thrown in c:\xampp\htdocs\oop\index.php on line 10.
even if instantiate object of author
class in constructor, keep getting string in question
class once try use 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 author's name?", new author("josel", "parayno")); echo $question->getquestion(); echo $question->getfullname();
$question not have getfullname method. method getfullname exists in class author. , after creating , "sending" question, when created method getfullname available in class question private $author property.
but if want athor name follow code, need try
$question->getauthor()->getfullname();
and if this, take error again, becouse in question->getauthor return $this, , in case question object. getting author name question object should follow:
- fix getauthor this
public function getauthor() { $firstname = $this->author->getfirstname(); $lastname = $this->author->getlastname(); return $this->author; }
- rewite call name in index.php this
echo $question->getauthor()->getfullname();
Comments
Post a Comment