How to call super in PHP?

前端 未结 2 358
生来不讨喜
生来不讨喜 2020-12-24 04:23

I have a classB which extends classA.

In both classA and classB I define the method fooBar

相关标签:
2条回答
  • 2020-12-24 05:16
    parent::fooBar();
    

    Straight from the manual:

    The ... double colon, is a token that allows access to ... overridden properties or methods of a class.

    ...

    Example #3 Calling a parent's method

    <?php
    class MyClass
    {
        protected function myFunc() {
            echo "MyClass::myFunc()\n";
        }
    }
    
    class OtherClass extends MyClass
    {
        // Override parent's definition
        public function myFunc()
        {
            // But still call the parent function
            parent::myFunc();
            echo "OtherClass::myFunc()\n";
        }
    }
    
    $class = new OtherClass();
    $class->myFunc();
    ?>
    
    0 讨论(0)
  • 2020-12-24 05:21

    Just a quick note because this doesn't come up as easy on Google searches, and this is well documented in php docs if you can find it. If you have a subclass that needs to call the superclass's constructor, you can call it with:

    parent::__construct(); // since PHP5
    

    An example would be if the super class has some arguments in it's constructor and it's implementing classes needs to call that:

    class Foo {
    
      public function __construct($lol, $cat) {
        // Do stuff specific for Foo
      }
    
    }
    
    class Bar extends Foo {
    
      public function __construct()(
        parent::__construct("lol", "cat");
        // Do stuff specific for Bar
      }
    
    }
    

    You can find a more motivating example here.

    0 讨论(0)
提交回复
热议问题