Вопрос

What I was really looking for was a magic method __toArray for my class, but I guess such a thing doesn't exist, and the ArrayAccess interface doesn't match what I'm looking for.

I would like to be able to return a json_encoded representation of my object when serialize is called on it, instead of the traditional PHP string representation.

Here is an example of my code, which I can't get to work.

<pre>
<?php
class A implements Serializable {
    private $a,
        $b,
        $c;

    public function __construct () {
        $this->a = 1;
        $this->b = 2;
        $this->c = 3;
    }

    public function serialize () {
        return json_encode(array (
            'a' => $this->a,
            'b' => $this->b
        ));
    }

    public function unserialize ($serialized) {
    }
}

echo '<b>PHP version:</b> ',
    phpversion(),
    PHP_EOL,
    '<b>Serialized:</b> ',
    serialize(new A());
?>
</pre>

I know I'm implementing the interface correctly, because if I omit one of the methods, it displays an error. However, this is what my script returns:

PHP version: 5.4.14

Serialized: C:1:"A":13:{{"a":1,"b":2}}

If I instantiate an instance of A and call it like any old method, like so:

$a = new A();
$a->serialize();

It works as expected:

PHP version: 5.4.14

Serialized: {"a":1,"b":2}

Although this kind of defeats the purpose of using the Serializable interface.

Any thoughts?

Thanks.

Это было полезно?

Решение

What about http://php.net/manual/fr/jsonserializable.jsonserialize.php?

Like this :

$ cat test.php
<?php
class A implements JsonSerializable {
    private $a,
        $b,
        $c;

    public function __construct () {
        $this->a = 1;
        $this->b = 2;
        $this->c = 3;
    }

    public function jsonSerialize() {
        return [
            'a' => $this->a,
            'b' => $this->b
        ];
    }

}
echo json_encode(new A(), JSON_PRETTY_PRINT);
$ php test.php 
{
    "a": 1,
    "b": 2
}

But there is no unserialize function.

Do you really need to call serialize on it?

Другие советы

That is not how the Serializable interface works.

The output in your second example doesn't have any information about the class. serialize() should return only the string representation of the data you need to unserialize from that object, which is still stored with some class information in the standard PHP serialization format.

The same data returned from your serialize() method (JSON string), will be passed to the unserialize() method, so there you have to pass it to json_decode() and set its properties yourself.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top