根据 PHP 文档,
对象接口允许您创建指定类必须实现哪些方法的代码,而无需定义这些方法的实现方式。
因此,接口就像一个具有预定义方法的类,仍然需要使用 -> 符号来访问
但是,ArrayAccess 接口提供对对象作为数组的访问。可以使用 $object->property 和 $object["property"]
我无法理解 ArrayAccess 如何使更改对象语法成为可能。我编写了一段代码来尝试复制 ArrayAccess 方法仅一个的效果,但它抛出错误
// Using the PHP ArrayAccess Interface
namespace A {
class myclass implements \ArrayAccess {
public function offsetExists($offset) { return true; }
public function offsetGet($offset) {
// changed behaviour
return $this->{$offset} ?? null;
}
public function offsetSet($offset, $value) {}
public function offsetUnset($offset) {}
}
$myclass = new myclass();
$myclass->access = 'Interface';
echo $myclass['access']; // "Interface"
};
//Trying to implement my own ArrayAccess Interface
namespace B {
interface MyArrayAccess {
public function offsetGet($offset);
}
class myclass implements MyArrayAccess {
public function offsetGet($offset) {
// change behaviour
return $this->{$offset} ?? null;
}
}
$myclass = new myclass();
$myclass->access = 'Interface';
echo $myclass['access']; // Fatal error: Uncaught Error: Cannot use object of type B\myclass as array
}
请帮我正确解释一下。谢谢
Copyright 2014-2026 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号