【问题标题】:Covariance (OOP) in PHP - how does it work [duplicate]PHP中的协方差(OOP)-它是如何工作的[重复]
【发布时间】:2017-12-10 12:43:41
【问题描述】:
class Param() {
}
class Subparam extends Param {
}

class Base {

  function mymethod(Param a) {
  }

}

class Sub extends Base {

 function mymethod(Subparam a) {
 }

}

在 PHP 中,这会导致警告:Declaration should be compatible with Base->mymethod(a : \Param)

除了仅使用注释之外,我还能做些什么来防止这种情况发生?

【问题讨论】:

  • 你真的不能。

标签: php oop covariance


【解决方案1】:

您可以使用界面:

interface Test {
}
class Param implements Test  {
}
class Subparam extends Param implements Test {
}

class Base {

  function mymethod(Test $a) {
  }

}

class Sub extends Base {

 function mymethod(Test $a) {
 }

}

【讨论】:

  • 这如何指定Sub::mymethod() 只能用Param 对象调用?
  • 出现错误。我改变了它:)
  • 我仍然不明白这如何使方法协变。
  • 由于Param实现Test,这将允许$sub->mymethod(new Param),这是不应该被允许的。
  • 这不是协方差。
【解决方案2】:
class Param() {
}
class Subparam extends Param {
}

class Base {

  function mymethod(a) {
    // Remove the parameter type from the method declaration.
    if (a !instanceof Param) {
      throw new \Exception('Paramater type should be of 'Param.');
    }

}

class Sub extends Base {

 function mymethod(a) {
 }

}

这应该让你接近。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-19
    • 1970-01-01
    • 1970-01-01
    • 2020-09-15
    • 2013-12-06
    相关资源
    最近更新 更多