gpt4 book ai didi

php - PHP 文档不一致?

转载 作者:可可西里 更新时间:2023-11-01 06:37:08 25 4
gpt4 key购买 nike

我目前正在阅读这里的 PHP 规范:https://github.com/php/php-langspec

  1. 现在,我看到了 list-intrinsic 规范 here , 它声明对于如下所示的 list-intrinsic 构造,simple-assignment-expression 的右侧 必须是指定数组的表达式:

    list ( list-expression-listopt ) = expression

  2. 但是 list 的文档来自 php.net here , 给出了一个包含这个的例子:

    $result = $pdo->query("SELECT id, name, salary FROM employees");
    while (list($id, $name, $salary) = $result->fetch(PDO::FETCH_NUM)) {
    //output $id, $name and $salary
    }

问题在于,如果没有更多的行,PDOStatement::fetch(PDO::FETCH_NUM) 返回 FALSE。但是 assignment-expression 的右侧必须是数组 - 而 FALSE 不是数组。所以这会导致 fatal error ,对吧?

我是否遗漏了规范中的某些内容,或者这真的是不一致?


According PHP bugreport

最佳答案

这是在 php 的实现中故意完成的,以允许这段可疑的代码:

while (list($key, $value) = each($array)) {
// ...
}

each() 的结果可能是 false,否则会触发严重的错误,因此虽然这种行为看似违反规范,但主要是为了保持向后兼容性。

下一个版本的 PHP 有可能(尽管不太可能)废除这种行为,但在这一点上我建议可以编辑规范以反射(reflect)这种特殊的人工制品,尽管隐含的未定义行为也可以用于该目的: )

令人讨厌的细节

可以找到此代码 here ;目前,右侧表达式支持:

  1. 一个数组,
  2. 一个实现 ArrayAccess 的对象,
  3. 其他。

在“其他”的情况下,它只会将 null 分配给所有列表变量。

更新

Nikita Popov作为 pull request 的一部分提出了以下规范更新:

list-intrinsic must be used as the left-hand operand in a simple-assignment-expression of which the right-hand operand must be an expression that designates an array or object implementing the ArrayAccess interface (called the source array).

...

This intrinsic assigns one or more elements of the source array to the target variables. On success, it returns a copy of the source array. If the source array is not an array or object implementing ArrayAccess no assignments are performed and the return value is NULL.

(强调更改)

关于php - PHP 文档不一致?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28343884/

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