Search code examples
phpoverridingstatic-functions

In function overridding why we not declare it static


I have a child class where I define a static function:

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);

When I run my program it shows error:

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

How come?


Solution

  • Issue

    PHP is kinda strict when we talk about inheritance, extending and overriding methods (those are not functions! Do not get fooled by function keyword.).

    If parent has static method, then your override can only be static. You cannot turn static into non-static.

    This works both ways. You cannot override non-static method to be static one. This would violate many inheritance rules.

    When you override methods, the rules are as follows:

    1. Child's method name must be exactly the same as parent's method name
    2. Child's method must accept the same number of arguments. If some default values are defined, they must be the same
    3. Type of method's calling (static or not) must be preserved.

    Those can be not the all rules that apply. For more information go to Manual

    Solution

    Either change parent's method to be static or remove static keyword from child's method.