Hello i have one class as child and one class as parent. One class again as Writer info.
I get an error when passing array of two objects (obj. from two class child) in writer class function. I get this :
Catchable fatal error: Argument 1 passed to PersonWriter::setData() must be an instance of
Person, array given, called in C:\xampp\htdocs\php\oop\book\Person.php on line 62 and
defined in C:\xampp\htdocs\php\oop\book\Person.php on line 40
My questions is :
- I have one child class that directly descendant of parent class. And i create method using Parent class type. Why not work?
- How to fix that?
This is my code :
<?php
// Class Person
class Person {
public $name;
public $gender;
public $age;
public function __construct($name, $gender, $age) {
$this->name = $name;
$this->gender = $gender;
$this->age = $age;
}
public function getInfo() {
$info = "Name : $this->name<br/>Gender : $this->gender<br/>Age : $this->age";
return $info;
}
}
// Class Mahasiswa
class Mahasiswa extends Person {
public $npm;
public function __construct($npm, $name, $gender, $age) {
parent::__construct($name, $gender, $age);
$this->npm = $npm;
}
public function getInfo() {
$info = "NPM : $this->npm<br/>";
$info .= parent::getInfo();
return $info;
}
}
// Class PersonWriter
class PersonWriter {
private $persons = array();
public function setData(Person $persons) {
$this->persons[] = $persons;
}
public function write() {
$str = "";
foreach ($this->persons as $person) {
$str = "Name : $person->name<br/>";
$str .= "Gender : $person->gender<br/>";
$str .= "Age : $person->age<br/>";
}
echo $str;
}
}
// Create 2 objects
$mhs = new Mahasiswa("201143579091","Fandi Akhmad", "L", 21);
$mhs2 = new Mahasiswa("201143579092","Annisya Ferronica", "P", 19);
// Add objects to Array
$persons = array($mhs, $mhs2);
$writer = new PersonWriter();
$writer->setData($persons);
$writer->write();
?>
Answer :
- In example code that checked as answer below.
- Oh okay, i catch it. I know understand my function setData(Person $persons) Because in my book not tell the explanation.
Now i add the person object to array like :
<?php ...
$writer->setData($mhs);
$writer->setData($mhs2);
?>
And i edited my function like this :
public function write() {
$str = "";
foreach ($this->persons as $person) {
$str = "Name : $person->name<br/>";
$str .= "Gender : $person->gender<br/>";
$str .= "Age : $person->age<br/>";
echo "<br/>";
echo $str;
}
}
And it works now.
Personinstance in the method, but want to pass an array.Person.