gpt4 book ai didi

PHP 5.6 : ArrayAccess: Function isset calls offsetGet and causes undefined index notice

转载 作者:可可西里 更新时间:2023-10-31 23:50:44 26 4
gpt4 key购买 nike

我编写了实现 ArrayAccess 接口(interface)的简单 PHP 类:

class MyArray implements ArrayAccess
{
public $value;

public function __construct($value = null)
{
$this->value = $value;
}

public function &offsetGet($offset)
{
var_dump(__METHOD__);

if (!isset($this->value[$offset])) {
throw new Exception('Undefined index: ' . $offset);
}

return $this->value[$offset];
}

public function offsetExists($offset)
{
var_dump(__METHOD__);

return isset($this->value[$offset]);
}

public function offsetSet($offset, $value)
{
var_dump(__METHOD__);

$this->value[$offset] = $value;
}

public function offsetUnset($offset)
{
var_dump(__METHOD__);

$this->value[$offset] = null;
}
}

在 PHP 7 中正常,但在 PHP 5.6 和 HHVM 中出现问题。

如果我在 undefined index 上调用函数 isset(),PHP 将调用 offsetGet() 而不是 offsetExists() 这将导致未定义索引通知。

在 PHP 7 中,只有当 offsetExists() 返回 true 时,它才会调用 offsetGet(),因此没有错误。

我认为这与 PHP bug 62059 有关.

该代码在 3V4L 可用,因此您可以看到哪里出了问题。如果索引未定义,我又添加了几个调试调用并抛出异常,因为通知未在 3V4L 中显示: https://3v4l.org/7C2Fs

不应该有任何通知,否则 PHPUnit 测试将失败。我该如何解决这个错误?

最佳答案

看起来这是旧版本 PHP 和 HHVM 中的 PHP 错误。由于不再支持 PHP 5.6,因此不会修复此错误。

快速修复是在方法 offsetGet() 中添加额外的检查,如果索引未定义则返回 null:

class MyArray implements ArrayAccess
{
public $value;

public function __construct($value = null)
{
$this->value = $value;
}

public function &offsetGet($offset)
{
if (!isset($this->value[$offset])) {
$this->value[$offset] = null;
}

return $this->value[$offset];
}

public function offsetExists($offset)
{
return isset($this->value[$offset]);
}

public function offsetSet($offset, $value)
{
$this->value[$offset] = $value;
}

public function offsetUnset($offset)
{
$this->value[$offset] = null;
}
}

请参阅 3V4L 处的代码和 zerkms的评论(firstsecondthird)。

关于PHP 5.6 : ArrayAccess: Function isset calls offsetGet and causes undefined index notice,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51697914/

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