Skip to content

Instantly share code, notes, and snippets.

@CSalih
Last active December 14, 2021 13:55
Show Gist options
  • Save CSalih/b2a1fa21bd6d016c4a71c42b108a4db7 to your computer and use it in GitHub Desktop.
Save CSalih/b2a1fa21bd6d016c4a71c42b108a4db7 to your computer and use it in GitHub Desktop.
Converts an PHP Object to Array

Interface

interface Arrayable {
    public function toArray() : array;
}

Using a Trait:

trait JsonSerializableTrait {
    public function jsonSerialize()
    {
        // or array_filter(get_object_vars($this)); if you don't want to include null values
        return get_object_vars($this);
    }
}

Example:

class ClassToArray implements \JsonSerializable, Arrayable
{
    use JsonSerializableTrait;
    
    private $propOne = "one";
    private $propTwo = "two";
}

$toArrayTest = new ClassToArray();

assert($toArrayTest->jsonSerialize() == [ 'propOne' => 'one', 'propTwo' => 'two' ]);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment