在函数中覆盖为什么我们不将其声明为静态

In function overridding why we not declare it static

我有一个 child class,我在其中定义了一个静态函数:

class functionover
{
    function override($num1, $num2)
    {
        $total = $num1+$num2;
    }


}
class childfunctionover extends functionover
{
    static function override($num1, $num2)
    {
        $sum = $num1+$num2;
    }
}



functionover :: override(10, 20);

当我 运行 我的程序显示错误时:

Cannot make non static method functionover::override() static in class childfunctionover

怎么会?

问题

当我们谈论继承、扩展和覆盖方法时,

PHP 有点严格(那些不是函数!不要被 function 关键字愚弄。)。

如果 parent 有 static 方法,那么您的覆盖 只能 static。你不能把 static 变成 non-static.

这是双向的。您不能将 non-static 方法覆盖为 static 方法。这将违反许多继承规则。

重写方法时,规则如下:

  1. Child的方法名必须和parent的方法名完全一致
  2. Child 的方法必须接受相同数量的参数。如果定义了一些默认值,它们必须相同
  3. 必须保留方法调用的类型(static 或不)。

这些可能不是所有适用的规则。有关详细信息,请访问 Manual

解决方案

要么将 parent 的方法更改为 static,要么从 child 的方法中删除 static 关键字。