Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return parent::function in a function

class Test extends Parent {
   $a = 1;

   public function changeVarA() {
       $a = 2;
       return parent::changeVarA();
   }

}

Can Anyone please explain what does return parent::function(); it do ?

Thank you...! ;D

like image 340
AnteKo Avatar asked Mar 22 '23 13:03

AnteKo


1 Answers

This will call the function changeVarA in the parent class.

When a class extends another class, and both have the same function name, the parent:: call forces the parent version of the function to be called and used. The return part of it will simply return whatever the parent function returns after it completes:

<?php
class A {
    function example() {
    echo "Hello Again!\n";
    }
}

class B extends A {
    function example() {
    echo "Hello World\n";
    parent::example();
    }
}

$b = new B;

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

output:

Hello World
Hello Again!

The example is taken from the PHP documentation which you really should take a look at.

like image 162
Fluffeh Avatar answered Apr 05 '23 23:04

Fluffeh