This needs a Person
not an array;
$writer->setData($persons);
This will work;
$p = new Person("Jake", "male", 29);
$writer->setData($p);
This is because the setData
function requires a Person
object;
public function setData(Person $persons) {
$this->persons[] = $persons;
}
If you want it to accept an array do;
public function setData(array $persons) {
$this->persons[] = $persons;
}
Or you can make it accept anything you want, by removing the hint;
public function setData($persons) {
$this->persons[] = $persons;
}
EDIT
I am assuming this is not your code, because if it were it would be perfectly obvious why its broke when passing in an array. Please learn the basics of OO before diving in two feet first and struggling. The error makes it obvious what the issue is. Here it is explained;
// You are meant to pass in a Person object here, it then appends that
// to an existing array of Persons
public function setData(Person $persons) {
$this->persons[] = $persons;
}
// This array of Persons is then iterated over in this function, this is
// where line 48 is,
public function write() {
$str = "";
// Here the foreach goes over the Persons array
foreach ($this->persons as $person)
{
// But the $person objects are being accessed like objects using the
// -> operator, so if you pass in an array it will fail because you do
// no access an array using ->
$str = "Name : $person->name<br/>";
$str .= "Gender : $person->gender<br/>";
$str .= "Age : $person->age<br/>";
}
echo $str;
}
You can change these lines to the following to access an array;
$str = "Name : " . $person['name'] . "<br/>";
$str .= "Gender : " . $person['gender'] . "<br/>";
$str .= "Age : " . $person['age'] . "<br/>";