【问题标题】:Way to get the output of an abstract function获取抽象函数输出的方法
【发布时间】:2017-06-16 05:38:27
【问题描述】:

我有一个带有抽象方法“运行”的抽象类。扩展此实现的子类运行并返回一个布尔值作为输出。 有没有办法可以在抽象类中获取运行(真/假)方法的状态。

我想要这个,因为我试图添加一些统计信息,因为有多少类失败/通过来执行 run 方法。我已经有很多类扩展了它,不想在其中添加任何东西并免费获得这些统计数据。

abstract class parent {
  // I need the status of the run method in here
  public abstract function run(); 
}

class child extends parent {
  public function run() {
   if (implementation) {
     return true;
     } else {
     return false;
     }
   }
}

帮助表示赞赏。

【问题讨论】:

    标签: php abstract-class base-class


    【解决方案1】:

    在调用抽象方法并获取结果的父级中定义一个非抽象方法。

    abstract class parent {
        private $run_result;
    
        public function run() {
            $this->run_result = $this->run_internal();
        }
        abstract protected function run_internal();
    }
    
    class child extends parent {
        protected function run_internal() {
            if (implementation) {
                return true;
            } else {
            return false;
            }
        }
    }
    

    【讨论】:

    • 但是我需要调用run()。上面的子类调用 run_internal 不调用 run()。
    • 子类不调用run_internal(),它实现它。当应用程序调用run()时父类调用它。
    猜你喜欢
    • 1970-01-01
    • 2020-06-18
    • 1970-01-01
    • 2011-05-25
    • 2013-09-23
    • 2017-09-03
    • 2016-05-04
    • 2012-09-21
    • 2019-07-14
    相关资源
    最近更新 更多