【问题标题】:When we receive an instance of a child object as a type-hinted parameter of a parent, why do we have a child object instead of a parent object?当我们收到一个子对象的实例作为父对象的类型提示参数时,为什么我们有一个子对象而不是父对象?
【发布时间】:2021-02-27 18:38:19
【问题描述】:

在下面的代码中,一个子实例被传递给由父类类型提示的函数“f”。我希望在函数中看到父对象(基于我们从 c++ 中的 oop 知道的),但是使用 PHP,我收到了子对象。谁能给我解释一下?

class ParentClass
{

}

class ChildClass extends ParentClass
{

}

function f(ParentClass $p)
{
    var_dump($p); // output: object(ChildClass)#1 (0) { }
}

f(new ChildClass);

【问题讨论】:

  • 根据我对 C++ 中 OOP 的了解,您还将获得 C++ 中子类的实例...
  • @obe 当类型提示子对象给父对象时,类型不应该改为父对象吗?
  • PHP 中的对象不能在运行时更改它们的类型,但这应该不是问题。派生(子)类的对象应该在需要父类对象的任何上下文中正确运行。这称为里氏替换原则。
  • C++ 完全一样。将对象的 runtime 类型传递给函数时,它不会改变,无论函数期望接收的形式参数的类型如何。只有编译时类型不同。

标签: php oop


【解决方案1】:

在这种情况下,由于 ChildClass 是从 ParentClass 扩展而来的,因此它具有 ParentClass 的所有功能,以及 ChildClass 中实现的任何功能。

函数 f(ParentClass $p) 需要 is_a($p, "ParentClass") 的对象,该对象由 ParentClass 类型的对象或扩展(例如 ChildClass)满足。

该特定函数 f(ParentClass $p) 中的任何代码都应仅依赖于 $p 具有来自 ParentClass 的函数,而不是来自 ChildClass 的函数。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-11-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-03
    相关资源
    最近更新 更多