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 unity第一人称射击小游戏,有demo,在原脚本的基础上进行修改以达到要求
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染