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_encode
d 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?