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 解决一个加好友限制问题 或者有好的方案
  • ¥15 关于#java#的问题,请各位专家解答!
  • ¥15 急matlab编程仿真二阶震荡系统
  • ¥20 TEC-9的数据通路实验
  • ¥15 ue5 .3之前好好的现在只要是激活关卡就会崩溃
  • ¥50 MATLAB实现圆柱体容器内球形颗粒堆积
  • ¥15 python如何将动态的多个子列表,拼接后进行集合的交集
  • ¥20 vitis-ai量化基于pytorch框架下的yolov5模型
  • ¥15 如何实现H5在QQ平台上的二次分享卡片效果?
  • ¥30 求解达问题(有红包)