Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP: How to call function of a child class from parent class

How do i call a function of a child class from parent class? Consider this:

class whale {   function __construct()   {     // some code here   }    function myfunc()   {   // how do i call the "test" function of fish class here??   } }  class fish extends whale {   function __construct()   {     parent::construct();   }    function test()   {     echo "So you managed to call me !!";   }  } 
like image 875
Sarfraz Avatar asked Dec 22 '09 08:12

Sarfraz


People also ask

How do you call a child function from a parent class?

To call a child's function from a parent component in React:Wrap the Child component in a forwardRef . Use the useImperativeHandle hook in the child to add a function to the Child . Call the Child's function from the Parent using the ref, e.g. childRef.

How do you call a method from child class to parent class in PHP?

We can't run directly the parent class constructor in child class if the child class defines a constructor. In order to run a parent constructor, a call to parent::__construct() within the child constructor is required.

Can parent class access child variables?

The reference holding the child class object reference will not be able to access the members (functions or variables) of the child class. This is because the parent reference variable can only access fields that are in the parent class.

Can child classes override properties of their parents?

In the same way that the child class can have its own properties and methods, it can override the properties and methods of the parent class. When we override the class's properties and methods, we rewrite a method or property that exists in the parent again in the child, but assign to it a different value or code.


1 Answers

That's what abstract classes are for. An abstract class basically says: Whoever is inheriting from me, must have this function (or these functions).

abstract class whale {    function __construct()   {     // some code here   }    function myfunc()   {     $this->test();   }    abstract function test(); }   class fish extends whale {   function __construct()   {     parent::__construct();   }    function test()   {     echo "So you managed to call me !!";   }  }   $fish = new fish(); $fish->test(); $fish->myfunc(); 
like image 153
FlorianH Avatar answered Oct 20 '22 03:10

FlorianH