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

DDD
Release: 2024-10-19 08:28:30
Original
929 people have browsed it

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:

<code class="php">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 !!";
  }
}</code>
Copy after login

Solution

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

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

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.

The above is the detailed content of How to Call Functions of Child Classes from Parent Classes in PHP?. 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!