According to PHP documentation,
Object Interfaces allow you to create code which specifies which methods a class must implement, without having to define how these methods are implemented.
Hence, an interface is like a class with predefined method which still needs to be accessed with the ->
symbol
However, the ArrayAccess Interface provides accessing of objects as arrays. Making it possible for an object to be accessed with both $object->property
and $object["property"]
I cannot understand how the ArrayAccess
makes it possible to change an object syntax. I’ve written out a code to try replicating the effect of just one of the ArrayAccess
method but it throws an error
// 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 Bmyclass as array
}
Please help me explain this properly. Thanks