简体   繁体   中英

How to call a non static method using static keyword?

I am just checking the OOPs static/non-static concept and found something strange.

I have heard that static method's output can be get by using static keyword with resolution operator(::) . But In my program I am getting non static method's value using static keyword. Can any one explain the program? I am getting confused.

<?php
error_reporting(E_ALL);

class parentclass
{
    protected function sum()
    {
        return 145;
    }
}

class childclass extends parentclass
{
    protected function sum()
    {
        return 125;
    }
}

class grandchild extends childclass
{
    function sum()
    {
        return 100;
    }

    function __construct()
    {
        echo static::sum(); // 100 as output but how
    }
}

$obj = new grandchild(); 
?>

Besides this If I am making function sum() of childclass as static like

class childclass extends parentclass
{
   protected static function sum()
   {
    return 125;
   }
 }

then also it is giving fatal error as following:

Fatal error: Cannot make non static method parentclass::sum() static in class childclass

But why I am not calling that function.

You can call a function statically, even if it is not declared as static , as long as you don't reference $this inside it.

That is why the original code works.

You cannot, however, change the signature of an inherited method.

Fatal error: Cannot make non static method parentclass::sum() static in class childclass

When you declare protected static function sum() in childclass , you are changing the signature of the inherited method from parentclass which is not specifically declared static .

Bottomline, you are trying to use some PHP quirks that I would recommend against. Yes, they work, but that doesn't mean you should use them.

Stick to a strict style of coding. Write separate methods for static and instance use and call them as intended.

You are using static as a Late Static Binding . But what you heard about was rather

class Foo
{
  static function bar() {}
}

$baz = Foo::bar();

I think to understand late static bindings a bit better you could write a variation of your code:

<?php
error_reporting(E_ALL);

class parentclass
{
    protected function sum()
    {
        return 145;
    }

    public function do_the_math()
    {
        printf('Static sum: %d, Self sum: %d', 
            static::sum(), 
            self::sum());
    }
}

class childclass extends parentclass
{
    protected function sum()
    {
        return 125;
    }
}

class grandchild extends childclass
{
    function sum()
    {
        return 100;
    }
}

$obj = new grandchild(); 
$obj->do_the_math();

Output:

Static sum: 100, Self sum: 145

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM