douzhongpi9734 2014-08-08 16:37
浏览 124
已采纳

PHP类可以返回它们正在实现的类型接口的对象吗?

When concreate classes implement interface, do they return object of type interface that they are implementing? In typical factory pattern scenario the concrete classes return object of type interface they are implementing (for java and C# this is true). Does this happen in case of PHP also?

Consider the following situation..

interface IUser
{
  function getName();
}

class User implements IUser
{
  public function __construct( $id ) { }

  public function getName()
  {
    return "Jack";
  }
}

class UserFactory
{
  public static function Create( $id )
  {
    return new User( $id );
  }
}

$uo = UserFactory::Create( 1 );
echo( $uo->getName()."
" );

Is object $uo an instance of type IUser or User, and why?

  • 写回答

2条回答 默认 最新

  • donglin8467 2014-08-08 16:54
    关注

    You never return an interface or a class, you return an object that implements the class of your choice which in turn will implement an interface.

    An interface or class is the declaration and definition portion of the object that you create while the object is variable that contains the properties. Any call you do to an object resolves to a class and the body of that function is executed, but the properties you access (the non-static ones) return to the object itself.

    When instanciating an object of a certain class, the object is OF that class. It cannot be of the type of an interface because an interface cannot be instanciated. On the other hand, you can use "instanceof" in PHP to determine if an object implements a certain interface or uses a specific class. Instanceof validates all interfaces implemented in all classes of the object, even the parent ones.

    So using:

    interface i {}
    interface i2 {}
    class a implements i {}
    class b extends a {}
    class c extends b implements i2 {}
    $o = new b();
    

    In this very case, $o is an "i", "a" and "b". All calls to instanceof with these class names will return true... But because $o is ob class b naturally, instanceof will never return true for the C class or the i2 interface.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 基于PLC的三轴机械手程序
  • ¥15 多址通信方式的抗噪声性能和系统容量对比
  • ¥15 winform的chart曲线生成时有凸起
  • ¥15 msix packaging tool打包问题
  • ¥15 finalshell节点的搭建代码和那个端口代码教程
  • ¥15 Centos / PETSc / PETGEM
  • ¥15 centos7.9 IPv6端口telnet和端口监控问题
  • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作
  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 海浪数据 南海地区海况数据,波浪数据