【问题标题】:How to extend php class to a class which ovverride it's functions如何将 php 类扩展为覆盖其功能的类
【发布时间】:2019-07-09 03:19:44
【问题描述】:

好的,我有这样的结构:

class Creature{
  public function sayHi(){
      echo "Hi";
  }
}

class HumanType extends Creature(){

}

class Human extends HumanType{

}

class Human232 extends Human{
      public function sayHi(){
        echo "Hello, bro";
      }
 }

class Human457 extend Human{

}

$Human = new Human232($id);
echo $Human->sayHi(); //Hello, bro

$Human2 = new Human457($id);
echo $Human2->sayHi(); //Hi

//And then I have this still to be implemented
class HumanCategory576{
     public function sayHi(){
      echo "Hi from the category!";
  }
} 

我当然有很多课程,例如: 人类457, 人类458, 人类459, 人类600, 人类601

还有: 人类类别576, HumanCategory577, 人类类别578, 人类类别579, HumanCategory580

我想要做的是实现 HumanCategory576 的方式,sayHi() 会打印“Hi from the category!”仅当(我想)继承它的 Human 类没有覆盖该函数时,例如 Human457。

我希望我已经足够清楚了。

我该怎么做?谢谢

【问题讨论】:

  • HumanCategory576 应该扩展一个类吗?
  • 只需在Human 类中实现这样的方法作为默认行为。 “覆盖”是指祖先(扩展)类的方法在派生(扩展)类中被覆盖。
  • 问题是我需要更多基于人类类别的默认方法。这可以通过基于 Human 类中的 Human Category 进行切换来完成。但是,必须有更好的方法,因为这样做意味着我将在每个默认函数中切换数百个案例。

标签: php class inheritance polymorphism


【解决方案1】:

我假设你打算让 class HumanCategory576 扩展另一个类。

您可以使用is_callable() 来检查HumanCategory576 parent 是否具有该功能:

is_callable('parent::sayHi'){
    parent::sayHi();
}else{
    echo "Hi from the category!";
}

请在 PHP 的文档中填写 is_callable

<?php

    class TestClass extends TestClassParent {

        /** @brief Object initialisation callback
            @returns void */
        public function __construct() {

            # do initialisation 

            # ...

            # if we have a parent 

            if(is_callable('parent::__construct')) {

                # then bubble up 

                parent::__construct();
            }
        }
    }
?>

【讨论】:

  • 这作为一个简单的直接继承 OOP 模式没有多大意义,因为当您不知道某个构造函数是否存在时,您也不知道它需要哪些参数。一个良好实现的 OOP 模式确实知道新类派生自的类层次结构。有时会使用这样的测试,例如在可能生成多个类的实例的工厂模式中。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-11-27
  • 2017-06-28
相关资源
最近更新 更多