7

I don't understand the concept of calling a parent method in PHP. The parent method is not static, yet it is called statically - normally PHP would throw an error/warning.

Question is, is this a quirk from PHP, or is this how it should be in OOP?

Taking the example from php.net:

<?php
class A {
    function example() {
        echo "I am A::example() and provide basic functionality.<br />\n";
    }
}

class B extends A {
    function example() {
        echo "I am B::example() and provide additional functionality.<br />\n";
        parent::example();
    }
}

$b = new B;

// This will call B::example(), which will in turn call A::example().
$b->example();
?>

http://php.net/manual/en/keyword.parent.php

In PHP 5, calling non-static methods statically generates an E_STRICT level warning.

http://php.net/manual/en/language.oop5.static.php

2

2 Answers 2

5

If you will look at the definition of static method you will see:

  1. Static methods are meant to be relevant to all the instances of a class rather than to any specific instance. - indeed this method is relevant to all children of the parent class.
  2. A static method can be invoked even if no instances of the class exist yet. - again, you never create an instance of the parent class to invoke the method.

So we can take this argument as an excuse for PHP. By the way, in C++ it is done the same way.

But there are other languages, where it is done like you said. For example, in JAVA, the parent method called like super.printMethod();, in C#, it is done like base.printMethod().

So in PHP it might be done for the parser simplicity, as they will need a specific edge case for such invocation parent->printMethod().

1
  • 1
    Now I wonder what the scope/context will be in the parent method, but that is outside of the question I asked. Time for some experiments, if I only took the time... Oct 7, 2016 at 9:38
2

That notification means that you can't call a non-statically defined method as static, but the call you did inside the method is not a static call, but a call to the parent class.

So this call will throw the E_STRICT warning:

$b = new B;
$b::example();

but your example will not

1
  • 4
    Then why is not written like parent->method() wouldn't that make more sense? Its confusing me. Oct 7, 2016 at 8:58

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.