douhuiqi3855 2018-08-17 21:12
浏览 167
已采纳

类型提示返回类型时,self和ClassName之间的区别

In PHP, when I specify a return type for a method that is supposed to return an instance of the class, I can do so like this:

class Foo  {
    public function bar(): self  { ... }
}

or:

class Foo  {
    public function bar(): Foo  { ... }
}

both seem to produce the same results / behavior.

What's the difference? Is one best practice over the other?

Thanks.

  • 写回答

1条回答 默认 最新

  • doubu0897 2018-08-18 09:21
    关注

    What's the difference?

    There is no difference. self is a keyword that refers to the class itself.

    You can think of it as an alternative name of the class being defined, thus in your example self is an alternative name of Foo. In other words, you can use self to replace Foo wherever you want, except right after the class keyword, of course.

    Here is an example:

    class Foo {
        const HELLO = 'Hello!';
    
        public function bar(): Foo {
            echo Foo::HELLO;
            return new Foo;
        }
    }
    

    Which is exactly the same as this:

    class Foo {
        const HELLO = 'Hello!';
    
        public function bar(): self {
            echo self::HELLO;
            return new self;
        }
    }
    

    Is one best practice over the other?

    No. Simply use whichever is most convenient or most useful to you.

    I usually prefer to use self so that if I need to rename the class, I only need to rename it in one place (right after class).

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 微信会员卡接入微信支付商户号收款
  • ¥15 如何获取烟草零售终端数据
  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?