"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to Call Functions of Child Classes from Parent Classes in PHP?

How to Call Functions of Child Classes from Parent Classes in PHP?

Published on 2024-11-04
Browse:381

How to Call Functions of Child Classes from Parent Classes in PHP?

How to Call Functions of Child Classes from Parent Classes in PHP

In PHP, a common task is invoking functions defined in child classes from within parent classes. Consider the following example:

class whale
{
  public function __construct()
  {
    // some code here
  }

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

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

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

Solution

One solution is to utilize abstract classes, which define essential functions that must be implemented by inheriting classes. Here's a modified code:

abstract class whale
{
  public function __construct()
  {
    // some code here
  }

  public function myfunc()
  {
    $this->test();
  }

  abstract public function test();
}

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

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

$fish = new fish();
$fish->test();
$fish->myfunc();

With this modification, you can invoke the test function of the fish class from the myfunc function of the whale class by calling $this->test(). This approach ensures that child classes must implement the test function.

Release Statement This article is reprinted at: 1729297696 If there is any infringement, please contact [email protected] to delete it
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3