gpt4 book ai didi

php - get_object_vars 根据 PHP 版本返回不同的结果

转载 作者:行者123 更新时间:2023-12-05 05:19:32 25 4
gpt4 key购买 nike

功能实现有时会因版本而异,但这并不奇怪,但不是这样......看:

$array = ["abc","def"];
$object = new stdclass();
foreach($array as $index => $value) {
$object->$index = $value;
}
var_dump(get_object_vars($object));

对于 5.6.x 然后例如7.0.17 和 7.1.3 我们得到:

array(2) { 
[0]=> string(3) "abc"
[1]=> string(3) "def"
}

但对于 7.0.0、7.0.16 和 7.1.0,我们得到:

array(2) { 
["0"]=> string(3) "abc"
["1"]=> string(3) "def"
}

演示:https://3v4l.org/jog4A

看到了吗?键是整数或字符串,具体取决于版本。

为什么?这些变化背后的原因是什么?为什么这在任何地方都没有记录?或者……是吗?

最佳答案

如果您更仔细地查看 3v4.org 输出中的版本,它在 7.0.0 至 7.0.16 和 7.1.0 至 7.1.2 中被破坏。所以这是 7.0 中引入的错误,并在 7.0.17 和 7.1.3(均于 2017 年 3 月 16 日发布)的两个事件版本中及时修复。

查看the PHP changelog我们可以看到相关的条目:

Fixed bug #73998 (array_key_exists fails on arrays created by get_object_vars).

这将我们引向 the bug tracker , 从那里到 commit dd9cf23457e21d2bda29dc92d437b9dbd14027b2 in th git repo :

BUG #73998: Numeric properties are not accessible from get_object_vars

修复涉及添加检查是否存在数字键,如果存在则跳过标记为“fast_copy”的 block 。

因此,这是在 PHP 7 开发期间进行的性能优化的不良副作用,现在已在所有受支持的版本中得到修复。

有趣的是,Andrea 在 bug 报告中评论说它与 an RFC to change the behaviour of object-to-array casts 密切相关。描述了一般问题:

Because arrays and objects have different restrictions versus the underlying HashTable type on what kinds of keys they can have, the Zend Engine must enforce their restrictions at a layer above HashTables, in the code implementing arrays and objects themselves. This means that if that code is bypassed and the underlying HashTables are modified directly, arrays and objects can exist with an invalid internal state.

以及 RFC 解决的具体案例:

For example, $arr = [0 => 1, 1 => 2, 2 => 3]; $obj = (object)$arr; produces an object with inaccessible properties named , 1 and 2, while $obj = new stdClass; $obj->{'0'} = 1; $obj->{'1'} = 2; $obj->{'2'} = 3; produces an array with the inaccessible keys "0", "1" and "2". The same issue also occurs when using get_object_vars().

RFC 在 7.2.0 中实现,因为它更改了记录的行为,但 get_object_vars() 的行为实际上是 7.0 中的无意更改,因此作为错误修复实现。

关于php - get_object_vars 根据 PHP 版本返回不同的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46000541/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com