Home > Backend Development > PHP Tutorial > How to Call Child Class Functions from Parent Class in PHP Using Abstract Classes?

How to Call Child Class Functions from Parent Class in PHP Using Abstract Classes?

Patricia Arquette
Release: 2024-10-19 08:25:02
Original
987 people have browsed it

How to Call Child Class Functions from Parent Class in PHP Using Abstract Classes?

Calling Child Class Functions from Parent Class

In PHP, it's possible to call a function from a child class within a parent class, but it requires careful planning.

Consider the following code example:

<code class="php">class whale { ... }
class fish extends whale { ... }</code>
Copy after login

In this example, we have a whale class and a fish class that inherits from it. The goal is to call the test() function from the fish class within the myfunc() function of the whale class.

Solution: Use Abstract Classes

To achieve this, we can leverage abstract classes. An abstract class enforces the implementation of certain methods in its child classes.

<code class="php">abstract class whale {
  function __construct() { ... }
  function myfunc() { $this->test(); }
  abstract function test();
}</code>
Copy after login

In the updated whale class, we now declare myfunc() and test() as abstract methods. myfunc() will call test(), which needs to be implemented in the child class.

<code class="php">class fish extends whale {
  function __construct() { parent::__construct(); }
  function test() { echo "So you managed to call me !!"; }
}</code>
Copy after login

In the fish class, we provide an implementation for test(). This ensures that the abstract requirements of the parent class are met.

With this setup, we can now call the test() function from fish within myfunc() of the whale class.

<code class="php">$fish = new fish();
$fish->test(); // Output: So you managed to call me !!
$fish->myfunc(); // Output: So you managed to call me !!</code>
Copy after login

By using abstract classes, we enforce proper inheritance and ensure that child classes implement the required methods. This allows us to call child class functions from parent classes seamlessly.

The above is the detailed content of How to Call Child Class Functions from Parent Class in PHP Using Abstract Classes?. For more information, please follow other related articles on the PHP Chinese website!

source:php
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template