Implement jsonSerializable in abstract class

// Just implement jsonSeralizable right?
class MyClass extends MyAbstractClass implements jsonSerializable  
public function jsonSerialize() {  
  return get_obj_vars($this);

Alright, that's easy enough.... wait.. Its only returning MyAbstractClass methods.

Crap I need to implement jsonSerializable in 30 classes that extend MyAbstractClass because I want to be able to json_encode the classes?

Turns out no. We just need Reflection.

Open up MyAbstractClass again and make sure you are implementing jsonSerializable -

abstract class MyAbstractClass implements jsonSerializable  

Then implement jsonSerialize as so -

public function jsonSerialize() {

    $reflection = new \ReflectionClass($this);
    $properties = [];
    foreach($reflection->getProperties() as $property) {
      $properties[$property->getName()] = $property->getValue($this);
    return $properties;


If you simply return get_object_vars($this) you are going to return the abstract class. With the \ReflectionClass($this) it grabs the child properties of the current class we are extending because we are calling jsonSerialize from from the class we extended from MyAbstractClass.

This also works with non abstract classes.