php - 覆盖功能不兼容

标签 php overriding arrayobject

长话短说

我想像这样从 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

问题

  1. 为什么覆盖 offsetSet() 不能用于上述代码,但 append() 可以?
  2. 如果我在 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/

相关文章:

php - ArrayObject 迭代

PHP ArrayObject 内部工作原理

php - 在 laravel 5 中删除文件的问题

php - PDO 出现错误

php - 仅显示已更改的列

php - Javascript 将内联变量传递给外部 : security issue?

c++ - 在 C++ 中用私有(private)函数覆盖公共(public)虚函数

Java无法重写构造函数中使用的方法: The method setupAnimationFrames() of type Slime must override or implement a supertype method

css - 使用 CSS 覆盖 DIV 中的字体大小

php - PHP 的 ArrayObject 是否有一个 in_array 等价物?