首页  >  文章  >  后端开发  >  如何在 PHP 中从父类中的子类调用函数?

如何在 PHP 中从父类中的子类调用函数?

DDD
DDD原创
2024-10-19 08:27:30186浏览

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

如何在 PHP 中从父类调用子类函数

问题:

考虑以下代码来说明挑战:

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

鉴于上面定义的类,我们如何从父类(“鲸鱼”)中有效地访问子类(“鱼”)的“测试”功能?

答案:

在这种情况下,PHP 中抽象类的概念提供了一个可行的解决方案。抽象类要求继承它的任何类必须实现特定的函数或方法。

修订的代码:

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

说明:

通过将“whale”声明为抽象类并包含抽象方法“test”,我们强制要求子类实现“test”功能。这允许“whale”类中的“myfunc”函数直接调用“test”。

注意:抽象类不允许对象实例化;因此,它们仅作为子类继承和实现必要方法的蓝图。

以上是如何在 PHP 中从父类中的子类调用函数?的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn