TL;DR
I want to override offsetSet($index,$value)
from ArrayObject
like this: offsetSet($index, MyClass $value)
but it generates a fatal error ("declaration must be compatible").
What & Why
I'm trying to create an ArrayObject
child-class that forces all values to be of a certain object. My plan was to do this by overriding all functions that add values and giving them a type-hint, so you cannot add anything other than values of MyClass
How
First stop: append($value);
From the SPL:
/**
* Appends the value
* @link http://www.php.net/manual/en/arrayobject.append.php
* @param value mixed <p>
* The value being appended.
* </p>
* @return void
*/
public function append ($value) {}
My version:
/**
* @param MyClass $value
*/
public function append(Myclass $value){
parent::append($value);
}
Seems to work like a charm.
You can find and example of this working here
Second stop: offsetSet($index,$value);
Again, from the SPL:
/**
* Sets the value at the specified index to newval
* @link http://www.php.net/manual/en/arrayobject.offsetset.php
* @param index mixed <p>
* The index being set.
* </p>
* @param newval mixed <p>
* The new value for the index.
* </p>
* @return void
*/
public function offsetSet ($index, $newval) {}
And my version:
/**
* @param mixed $index
* @param Myclass $newval
*/
public function offsetSet ($index, Myclass $newval){
parent::offsetSet($index, $newval);
}
This, however, generates the following fatal error:
Fatal error: Declaration of Namespace\MyArrayObject::offsetSet() must be compatible with that of ArrayAccess::offsetSet()
You can see a version of this NOT working here
If I define it like this, it is fine:
public function offsetSet ($index, $newval){
parent::offsetSet($index, $newval);
}
You can see a version of this working here
Questions
- Why doesn't overriding
offsetSet()
work with above code, butappend()
does? - Do I have all the functions that add objects if I add a definition of
exchangeArray()
next to those ofappend()
andoffsetSet()
?