因为我更喜欢面向对象的方法,所以我编写了自己的json类来处理json_last_error以进行解码和编码。
不知怎么的,我收到了一个关于json_decode方法深度属性的php警告。
json_decode方法的PHP核心api(eclipse-PDT)如下所示:
function json_decode ($json, $assoc = null, $depth = null) {}
到目前为止还不错,但如果我这样写我自己的课:
function my_json_decode ($json, $assoc = null, $depth = null) {
return json_decode($json, $assoc, $depth);
}
并尝试按以下方式运行:
$json = '{ "sample" : "json" }';
var_dump( my_json_decode($json) );
我收到以下警告:
Warning: json_decode(): Depth must be greater than zero in /
我错过什么了吗?我想如果我把一个属性的null传递给一个将属性本身设置为null的方法,应该没问题吧?!
使用:服务器:Apache/2.2.22(Unix)PHP/5.3.10
谢谢你的帮助!
[编辑]澄清我的理解泄露在哪里:
我使用的是Eclipse Indigo+PDT。org.eclipse.PHP.core.language的PDT PHP核心api与PHP.net所说的json_decode不同:
json_decode org.eclipse.php.core.language:
json_decode ($json, $assoc = null, $depth = null)
json_decode php.net:
json_decode ( string $json [, bool $assoc = false [, int $depth = 512 [, int $options = 0 ]]] )
Depth假设是一个数字和(int)null == 0
,因此您将0传递给$Depth。根据php手册,512是$depth的默认值http://php.net/manual/en/function.json-decode.php
Depth是json_decode的递归深度(应该是INTEGER)。有关更多详细信息,请参阅手册。
您正在做的是将$depth设置为0。由于json对象的深度是2。$depth的最小值必须是CCD_ 2。此外,您的代码在深度>2的任何值下都可以正常工作,但我建议使用默认值512(最初是128,后来在PHP 5.3.0中增加到512)
还要注意,assoc
必须是bool
值。
Imho,在这种情况下,面向对象的方法不值得bycicle发明。例如,只需从Yii框架的CJSON::decode方法中获取源代码(或者最好是整个类,它非常优秀)。
json_decode ( string $json [, bool $assoc = false [, int $depth = 512 [, int $options = 0 ]]] )
不能将NULL作为深度传递。因此,json_decode()的别名不正确。
如果不传入,这与函数和参数设置为null无关。问题是因为您将null传递给json_decode以获得深度。只需检查$assoc
和$depth
是否为空,如果它们不为空,则将它们适当地传递到json_decode中。此外,您应该明确$assoc
是一个bool,并使用默认值。
function my_json_decode ($json, $assoc = false, $depth = null) {
if ($assoc && !$depth)
return json_decode($json, $assoc);
else if ($depth)
return json_decode($json, $assoc, $depth);
return json_decode($json);
}
然而,我不确定为什么您需要这样做,因为php-json库会为您处理这件事。