长话短说
我想像这样从 ArrayObject
中覆盖 offsetSet($index,$value)
:offsetSet($index, MyClass $value)
但它会产生 fatal error (“声明必须兼容”)。
什么和为什么
我正在尝试创建一个 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);
}
但是,这会产生以下 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
如果我这样定义它,没问题:
public function offsetSet ($index, $newval){
parent::offsetSet($index, $newval);
}
You can see a version of this working here
问题
- 为什么覆盖
offsetSet()
不能用于上述代码,但append()
可以? - 如果我在
append()
和offsetSet()
?
最佳答案
abstract public void offsetSet ( mixed $offset , mixed $value )
由 ArrayAccess 声明接口(interface)而 public void append ( mixed $value )
没有相应的接口(interface)。显然 php 在后一种情况下比接口(interface)更“宽容”/宽松/无论什么。
例如
<?php
class A {
public function foo($x) { }
}
class B extends A {
public function foo(array $x) { }
}
“仅”打印警告
Strict Standards: Declaration of B::foo() should be compatible with A::foo($x)
同时
<?php
interface A {
public function foo($x);
}
class B implements A {
public function foo(array $x) { }
}
摆脱困境
Fatal error: Declaration of B::foo() must be compatible with A::foo($x)
关于php - 覆盖功能不兼容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13583192/