Home >Backend Development >PHP Tutorial >How to Call Functions from a Child Class Within a Parent Class in PHP?

How to Call Functions from a Child Class Within a Parent Class in PHP?

DDD
DDDOriginal
2024-10-19 08:27:30253browse

How to Call Functions from a Child Class Within a Parent Class in PHP?

How to Invoke Child Class Functions from Parent Class in PHP

Question:

Consider the following code to illustrate the challenge:

<code class="php">class whale
{
  function __construct()
  {
    // some code here
  }

  function myfunc()
  {
  // How do I call the "test" function of fish class from here??
  }
}

class fish extends whale
{
  function __construct()
  {
    parent::construct();
  }

  function test()
  {
    echo "So you managed to call me !!";
  }

}</code>

Given the classes defined above, how can we effectively access the "test" function of the child class ("fish") from within the parent class ("whale")?

Answer:

In this scenario, the concept of abstract classes in PHP provides a viable solution. An abstract class mandates that any classes inheriting from it must implement specific functions or methods.

Revised Code:

<code class="php">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();</code>

Explanation:

By declaring "whale" as an abstract class and including an abstract method "test", we enforce the requirement for child classes to implement the "test" function. This allows the "myfunc" function within the "whale" class to invoke "test" directly.

Note: Abstract classes do not permit object instantiation; therefore, they serve solely as a blueprint for child classes to inherit and implement the necessary methods.

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

Statement:
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