views:

33

answers:

1

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?

+4  A: 

You can access all member variables using get_object_vars():

foreach (get_object_vars($this) as $name => $value) ...
soulmerge
get_object_vars($this) seems like it's functionally equivalent to $this in terms of what it can access? If the child class's property's are private, neither $this nor get_object_vars($this) can access them from the parent class. If I change the properties in the child class to protected, then $this and get_object_vars($this) both work. So I think the answer is to make all of the child's properties protected instead of private.
Nick
Oh, you weren't mentioning they were declared members of the class (I thought you were adding random members just by assigning them to the object.) If the members are declared within the class, they must be at least protected if you want to access them from the parent.
soulmerge