|
php.net | support | documentation | report a bug | advanced search | search howto | statistics | random bug | login |
[2012-05-08 21:42 UTC] moisadoru at gmail dot com
Description:
------------
Calling json_encode() with an instance of a class that implements the
JsonSerializable has a reference to itself (recursion), PHP coredumps (CLI) or
exits with 'Allowed memory size of ... bytes exhusted'.
However, recursion in an instance of a class that does not implement the
JsonSerializable interface is detected, a warning is shown and the actual JSON
representation of the recursive reference is null.
In some situations, it tried to continously alocate memory, and eventually failed
with the 'Allowed memory size of XXXX bytes exhausted' message.
Test script:
---------------
<?php // file: jsonserialize.php
ini_set('display_errors', 'on');
error_reporting(-1);
set_time_limit(1);
ini_set('memory_limit','512M');
class JsonTest1 {
public $test;
public $me;
public function __construct() {
$this->test = '123';
$this->me = $this;
}
}
class JsonTest2 implements JsonSerializable {
public $test;
public function __construct() {
$this->test = '123';
}
public function jsonSerialize() {
return array(
'test' => $this->test,
'me' => $this
);
// same results with:
// return get_object_vars($this);
}
}
$obj1 = new JsonTest1();
echo json_encode($obj1);
echo "\n==\n";
$obj2 = new JsonTest2();
echo json_encode($obj2);
Expected result:
----------------
Warning: json_encode(): recursion detected in jsonserialize.php on line 34
{"test":"123","me":{"test":"123","me":null}}
==
Warning: json_encode(): recursion detected in jsonserialize.php on line 39
{"test":"123","me":{"test":"123","me":null}}
Actual result:
--------------
Warning: json_encode(): recursion detected in /var/www/jsonserialize.php on line
34
{"test":"123","me":{"test":"123","me":null}}
==
Segmentation fault (core dumped)
PatchesPull RequestsHistoryAllCommentsChangesGit/SVN commits
|
|||||||||||||||||||||||||||||||||||||
Copyright © 2001-2025 The PHP GroupAll rights reserved. |
Last updated: Sat Oct 25 19:00:01 2025 UTC |
Hi guys, i also getting the same issue. But i fixed like below. It's works for me. echo @json_encode(array or Object); I hope, it will help. Thanks.