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() m开发者_StackOverflow中文版ethod:
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?
You can access all member variables using get_object_vars()
:
foreach (get_object_vars($this) as $name => $value) ...
精彩评论