方法声明应与PHP中的父方法兼容

wai*_*933 102 php methods standards-compliance

Strict Standards: Declaration of childClass::customMethod() should be compatible with that of parentClass::customMethod()

PHP中出现此错误的可能原因是什么?我在哪里可以找到有关兼容性的信息

dav*_*nal 123

childClass::customMethod()有不同的参数,或不同的访问级别(公共/私人/受保护)parentClass::customMethod().

  • 具有相同的确切参数默认值也很重要.例如,`parentClass :: customMethod($ thing = false)`和`childClass :: customMethod($ thing)`会触发错误,因为child的方法没有为第一个参数定义默认值. (43认同)
  • 这在PHP 5.4中发生了变化,顺便说一句:*E_ALL现在包含error_reporting配置指令中的E_STRICT级别错误.见这里:http://php.net/manual/en/migration54.other.php (12认同)
  • 参数中缺少与号 (`&`) 也会触发此错误。 (2认同)

ldr*_*rut 36

此消息表示某些可能的方法调用可能在运行时失败.假设你有

class A { public function foo($a = 1) {;}}
class B extends A { public function foo($a) {;}}
function bar(A $a) {$a->foo();}
Run Code Online (Sandbox Code Playgroud)

编译器只根据A :: foo()的要求检查调用$ a-> foo(),这不需要参数.然而,$ a可能是B类的一个对象,它需要一个参数,因此调用在运行时会失败.

然而,这永远不会失败并且不会触发错误

class A { public function foo($a) {;}}
class B extends A { public function foo($a = 1) {;}}
function bar(A $a) {$a->foo();}
Run Code Online (Sandbox Code Playgroud)

因此,没有方法可能比其父方法具有更多必需参数.

当类型提示不匹配时也会生成相同的消息,但在这种情况下,PHP更具限制性.这给出了一个错误:

class A { public function foo(StdClass $a) {;}}
class B extends A { public function foo($a) {;}}
Run Code Online (Sandbox Code Playgroud)

就像这样:

class A { public function foo($a) {;}}
class B extends A { public function foo(StdClass $a) {;}}
Run Code Online (Sandbox Code Playgroud)

这似乎比它需要的更严格,我认为是由于内部.

可见性差异会导致不同的错误,但出于同样的基本原因.没有方法比其父方法更不可见.

  • 在你的上一个例子中 - 这里不应该有错误,因为它是合法的,stdClass $ a比混合$ a更具限制性.有办法解决这个问题吗?我的意思是在这种情况下PHP应该允许这样但它仍然会出错... (2认同)
  • 你的最后一个例子是类型安全的,所以它肯定是"比它需要的更严格".这可能是货物崇拜编程的一个例子,因为它与C++和Java中的多态性冲突http://en.wikipedia.org/wiki/Covariance_and_contravariance_(computer_science)#Contravariant_method_argument_type (2认同)

Saj*_*azy 22

如果您想保留OOP表格而不关闭任何错误,您还可以:

class A
{
    public function foo() {
        ;
    }
}
class B extends A
{
    /*instead of : 
    public function foo($a, $b, $c) {*/
    public function foo() {
        list($a, $b, $c) = func_get_args();
        // ...

    }
}
Run Code Online (Sandbox Code Playgroud)