【问题标题】:Declaration of child method should be compatible with that of parent method in PHP 5.3.13 [duplicate]子方法的声明应与 PHP 5.3.13 中的父方法的声明兼容 [重复]
【发布时间】:2023-03-31 09:20:01
【问题描述】:

我在运行 PHP 5.3.13 时遇到以下错误,我不明白为什么。

CustomCourse::toArray() 的声明应该与之兼容 BaseCourse::toArray()

这是我下面的 PHP 代码,虽然减少了重要的东西,以使帖子长度保持在需要的范围内。

我还应该补充一点,Course 类不公开toArray 方法。

我在 SO 上看到了其他类似的帖子,但似乎没有一个可以为我提供解决方案。

/**
* this is the CHILD class
*/
class CustomCourse extends BaseCourse {

   public function toArray() {
      $values = parent::toArray();
      // do some more with $values here
      return $values;
   }

}

/**
* this is the PARENT class
*/
class BaseContact extends Course {

   public function toArray($platform = GOLF_PLATFORM) {
      $values = array();
      $values['user_id'] = $this->getUserId();
      // do some more in here
      return $values;
   }

}

【问题讨论】:

  • @bcmcfc 这个答案的问题是它没有回答我的问题(见我的帖子)。这个childClass::customMethod() has different arguments, or a different access level (public/private/protected) than parentClass::customMethod(). 不适用于我。
  • 确实如此 - 您的两个 toArray() 方法具有不同的签名:BaseCourse 实现了一个带有参数和默认值的 toArray,CustomCourse 覆盖它并且没有在其签名中定义参数或默认值。跨度>
  • 您的子类没有扩展您的父类。这是问题中的错字吗?而且,为什么您认为该链接不能回答您的问题?您刚刚接受了与此类答案完全相同的副本。

标签: php oop object inheritance php-5.3


【解决方案1】:

这似乎是 PHP 报告的严格错误。

讨论如下:Declaration of Methods should be Compatible with Parent Methods in PHP

对于解决方案,您需要对两种方法使用相同的声明。

class CustomCourse extends BaseCourse {
    function toArray($platform=GOLF_PLATFORM) {
        //do something
    }
}

或者,您可以在 php.ini 文件中关闭严格的错误检查。

【讨论】:

  • 关闭错误总是一个坏主意。
  • 关闭严格错误可以去掉很多通知。应始终保持警告和实际错误。
  • 恕我直言通知不会白白显示。在这种情况下,概念错误是在具有一个签名的接口中声明一个方法,然后在具体化中使用不同的方法。由于 PHP 不支持经典方法重载,因此签名应该始终相同。您的第一个建议是解决方案,隐藏错误永远不是解决方案。
  • 我完全同意。但是,我不想给这个选项。
猜你喜欢
  • 1970-01-01
  • 2011-03-08
  • 2016-06-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多