dongtuo3795 2019-06-08 21:25
浏览 98

PHP:重构具有不同返回类型的覆盖方法的好方法

The return type of a method in a base class has changed. What is a good way to refactor the child method to keep its current return type?

In the following example there is the Database class, which now returns a date as a simple string. The inheriting class, on the other hand, overrides getDate and should still return a DateTime.

Note: The implementation in the base class cannot be changed.

Idea: Renaming the getDate method in the DoStuff class.

class Database
{
    public function getDate(): string
    {
        return '01-01-0001';
    }
}

class DoStuff extends Database
{
    public function getDate(): DateTime
    {
        return DateTime::createFromFormat('d-m-Y', parent::getDate());
    }
}

Are there best practices to solve such a problem? Many thanks for the help.

  • 写回答

1条回答 默认 最新

  • dpzbzp8728 2019-08-22 00:06
    关注

    In that case, the simple way that i see is to create a function that do the conversion, that function would return the DateTime, and you wouldn't need override the getDate:

    class DoStuff extends Database
    {
        public function pickDate(): DateTime
        {
            return DateTime::createFromFormat('d-m-Y', $this->getTime());
        }
    }
    

    I hope i've helped

    评论

报告相同问题?

悬赏问题

  • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?