PHP __toArray() or __toObject() override?

class, overriding, php, tostring

Solution

In php 5.4 and above, if your class impliments `JsonSerializable`, you can add a `jsonSerialize` method that will be called by `json_encode`:

<?php
class MyClass implements JsonSerializable
{
    public $foo;

    public function jsonSerialize() {
        return array(
            "foo"=>$this->foo,
            "name"=>"MyClass"
        );
    }
}

$x = new MyClass();
$x->foo = "hello";
echo json_encode($x);

Will print:

{"foo":"hello","name":"MyClass"}

Problem

Is there an equivalent to get a reorganized standardized object from a normal class? Something that works along the same lines as PHP's __toString() override method. Okay, so I have this method that grabs a bunch of stations, and returns an object model, which handles a bunch of other methods to get other related data. So in this instance when I call the object that contains the locations "$locations" I want to get back either a flat associative array of object properties, or an array of objects that I can easily encode to JSON. If I get an array of location objects back, I just want $location to be directly converted to a JSON string. Just like if I were to refer to $location as a location object that contained __toString() and it would automatically produce a string representation. In this case I want an standard object or array, and not a string. Is there a way to do this? Code sample below: ``` public function stnSearch() { $locations = DBO::getInstance()->query(" SELECT " . DBO_Location::COLUMNS . " FROM " . DBO_Location::TABLE_NAME . " AS a WHERE a.title LIKE '%" . $_REQUEST['query'] . "%' ")->fetchAll(PDO::FETCH_CLASS, DBO_Location::MODEL); Util::debug($locations); // want this to produce a standard object for each model without having to do an additional loop exit(); } ```

Original source