从 PHP 7.1.x 迁移到 PHP 7.2.x json_decode() 更改

Migrating from PHP 7.1.x to PHP 7.2.x json_decode() change

The official doc 说:

The json_decode() function option, JSON_OBJECT_AS_ARRAY, is now used if the second parameter (assoc) is NULL. Previously, JSON_OBJECT_AS_ARRAY was always ignored.

此代码 (AFAIK) 完成此更改和条件:

<?php

$an_object = new StdClass();
$an_object->some_atrribute = "value 1";
$an_object->other_atrribute = "value 2";

//an object
print_r($an_object);

$encoded = json_encode($an_object);

//here (null is passed in the second parameter)
$output = json_decode($encoded,null,512);

//using 7.2 should be array, however it is an object
print_r($output);

//array
$output = json_decode($encoded,true);
print_r($output);

但是只有最后一个打印,打印为数组。

我理解错了吗?

勾选 function signature:

mixed json_decode ( string $json [, bool $assoc = FALSE 
  [, int $depth = 512 [, int $options = 0 ]]] )

options

Bitmask of JSON decode options. Currently there are two supported options. The first is JSON_BIGINT_AS_STRING that allows casting big integers to string instead of floats which is the default. The second option is JSON_OBJECT_AS_ARRAY that has the same effect as setting assoc to TRUE.

这意味着您可以将第四个参数设置为JSON_OBJECT_AS_ARRAY,即使您没有将第二个参数设置为true 出于某种原因,而是将其设置为 null。但是这个第四个参数的默认值为 0,这意味着如果只有第二个参数设置为 null.

则没有转换(从对象到数组)

这里 the shortened demo 显示了不同之处:

$an_object = new StdClass();
$an_object->attr = 'value';

$encoded = json_encode($an_object);
print_r( json_decode($encoded, true, 512, JSON_OBJECT_AS_ARRAY)  );
print_r( json_decode($encoded, false, 512, JSON_OBJECT_AS_ARRAY) );
print_r( json_decode($encoded, null, 512, JSON_OBJECT_AS_ARRAY)  );

在这里,您将看到数组和对象作为所有 PHP 版本中第一次和第二次解码操作的结果打印出来。但是第三个操作只会从 PHP 7.2.0.

开始生成数组