phpinheritance

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 !!";
  }

}

Solution

  • 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();