如果另一个值不可用,偏移参数将设置为 NULL 在 php 中这意味着什么?

The offset parameter will be set to NULL if another value is not available what does it mean in php?

我正在为我的最后一年项目学习 ArrayAccess 界面。不知道什么时候ArrayAccess::offsetSet()offset参数设置为NULL.如 php.net.

中所述

Note: The offset parameter will be set to NULL if another value is not available, like in the following example.

<?php
$arrayaccess[] = "first value";
$arrayaccess[] = "second value";
print_r($arrayaccess);
?>

The above example will output:

Array
(
    [0] => first value
    [1] => second value
)

那么这里的NULL是什么概念呢?谁能告诉我?

引用 Link http://php.net/manual/en/arrayaccess.offsetset.php.

谢谢!

你提到了 ArrayAccess,这是接口,如果你在你的 class 中实现它 - 你将能够使用你的 class 作为数组。

您从手册中复制了关于 offsetSet 方法的句子

Note: The offset parameter will be set to NULL if another value is not available, like in the following example.

这里的例子不是很正确,所以我再准备一个:

http://sandbox.onlinephpfunctions.com/code/baedfadc9bd6bbfbde5ef7152e8c4e7d4a1d99e2

输出为:

this is MyTest::offsetSet offset: NULL; value: 'first value'
this is MyTest::offsetSet offset: NULL; value: 'second value'

如果你没有在代码中设置offset参数,你可以看到它是NULL,但是如果你使用这样的代码:

$arrayOffset[3] = "third value";

偏移参数将为 3

更新: 回答你的问题:

没有。如果你想同时支持插入和更新。您应该在 offsetSet 方法中实现此逻辑。例如:

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

正如我们所了解的,ArrayAccess 接口的 offsetSet() 方法提供了处理 赋值 值到 [=实现对象的 34=]偏移量 ArrayAccess:

public function offsetSet($offset, $value) 
{
     if ($offset === null) { 
         echo "Offset is NULL!"; 
     } else {
         echo "You assigned '$value' to '$offset'."; 
     }
}

当我们指定一个键为ArrayAccess对象的偏移量赋值时,PHP将键传递给offsetSet()

$arrayAccess['name'] = 'Alex'; 
// Outputs: "You assigned 'Alex' to 'name'." 

然而,如果我们不提供密钥,PHP 将 offsetSet() 的第一个参数的值设置为 null

$arrayAccess[] = 'Alex'; 
// Outputs: "Offset is NULL!" 

此语法类似于数组在未指定偏移量时执行 push 操作的方式:

$array = []; 
$array[] = 'Alex'; 

当我们实现 ArrayAccess 接口的 offsetSet() 方法时,我们可以选择模仿这种行为,或者我们可以执行不同的行为,例如如果我们不这样做则抛出异常想要支持空偏移量。 ArrayAccess 对象不一定需要 复制数组的行为。