Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call super in PHP?

Tags:

oop

php

I have a classB which extends classA.

In both classA and classB I define the method fooBar().

In fooBar() of classB I want to call fooBar() of classA at the beginning.

Just the way I'm used to, from Objective-C. Is that possible in PHP? And if so, how?

like image 948
openfrog Avatar asked Dec 25 '09 20:12

openfrog


People also ask

When super () is called?

Super is called when we want to inherit some of the parameters from the parent class. It is not compulsory as the compiler always call the default constructor.

What is super keyword in PHP?

The super keyword is used to call the constructor of its parent class to access the parent's properties and methods. Tip: To understand the "inheritance" concept (parent and child classes) better, read our JavaScript Classes Tutorial.

What is PHP super class?

Inheritance allows you to write the code in the parent class and use it in both parent and child classes. The parent class is also called a base class or super class. And the child class is also known as a derived class or a subclass. To define a class inherits from another class, you use the extends keyword.


2 Answers

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(); ?> 
like image 96
just somebody Avatar answered Oct 04 '22 16:10

just somebody


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.

like image 43
Spoike Avatar answered Oct 04 '22 18:10

Spoike