【发布时间】:2012-11-27 11:26:45
【问题描述】:
TL;DR
我想像这样从ArrayObject 覆盖offsetSet($index,$value):offsetSet($index, MyClass $value) 但它会产生一个致命错误(“声明必须兼容”)。
什么和为什么
我正在尝试创建一个ArrayObject 子类,它强制所有值都属于某个对象。我的计划是通过覆盖所有添加值的函数并给它们一个类型提示来做到这一点,所以除了MyClass的值之外你不能添加任何东西
如何
第一站:append($value);
来自 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) {}
我的版本:
/**
* @param MyClass $value
*/
public function append(Myclass $value){
parent::append($value);
}
似乎很有魅力。
You can find and example of this working here
第二站:offsetSet($index,$value);
同样,来自 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) {}
还有我的版本:
/**
* @param mixed $index
* @param Myclass $newval
*/
public function offsetSet ($index, Myclass $newval){
parent::offsetSet($index, $newval);
}
然而,这会产生以下致命错误:
致命错误:声明 命名空间\MyArrayObject::offsetSet() 必须是 兼容 ArrayAccess::offsetSet()
You can see a version of this NOT working here
如果我这样定义就好了:
public function offsetSet ($index, $newval){
parent::offsetSet($index, $newval);
}
You can see a version of this working here
问题
- 为什么覆盖
offsetSet()不适用于上述代码,但append()可以? - 如果我在
append()和offsetSet()的定义旁边添加exchangeArray()的定义,我是否拥有添加对象的所有功能?
【问题讨论】:
-
我知道我可以在调用父函数之前对函数进行类型检查,但除了知道我做错了什么之外,它不会给任何用户这个类是一个易于使用的类型提示。
标签: php overriding arrayobject