PHP: How do I access child properties from a method in a base object?
Posted
by Nick
on Stack Overflow
See other posts from Stack Overflow
or by Nick
Published on 2010-05-22T08:22:24Z
Indexed on
2010/05/22
8:30 UTC
Read the original article
Hit count: 231
I'd like for all of my objects to be able to return a JSON string of themselves.
So I created a base class for all of my objects to extend, with an AsJSON() method:
class BaseObject {
public function AsJSON()
{
$JSON=array();
foreach ($this as $key => $value)
{
if(is_null($value))
continue;
$JSON[$key] = $value;
}
return json_encode($JSON);
}
}
And then extend my child classes from that:
class Package extends BaseObject {
...
}
So in my code, I expect to do this:
$Box = new Package;
$Box->SetID('123');
$Box->SetName('12x8x6');
$Box->SetBoxX('12');
$Box->SetBoxY('8');
$Box->SetBoxZ('6');
echo $Box->AsJSON();
But the JSON string it returns only contains the BaseClass's properties, not the child properties.
How do I modify my AsJSON() function so that $this refers to the child's properties, not the parent's?
© Stack Overflow or respective owner