PHP:自我:: vs父母::带扩展 [英] PHP: self:: vs parent:: with extends

查看:67
本文介绍了PHP:自我:: vs父母::带扩展的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道当静态子类扩展静态父类时,使用self ::和parent ::有什么区别

I'm wondering what is the difference between using self:: and parent:: when a static child class is extending static parent class e.g.

class Parent {

    public static function foo() {
       echo 'foo';
    }
}

class Child extends Parent {

    public static function func() {
       self::foo();
    }

    public static function func2() {
       parent::foo();
    }
}

func()和func2()之间有什么区别吗?如果是,那又是什么呢?

Is there any difference between func() and func2() and if so then what is it ?

谢谢

致谢

推荐答案

                Child has foo()     Parent has foo()
self::foo()        YES                   YES               Child foo() is executed
parent::foo()      YES                   YES               Parent foo() is executed
self::foo()        YES                   NO                Child foo() is executed
parent::foo()      YES                   NO                ERROR
self::foo()        NO                    YES               Parent foo() is executed
parent::foo()      NO                    YES               Parent foo() is executed
self::foo()        NO                    NO                ERROR
parent::foo()      NO                    NO                ERROR

如果您正在寻找正确的使用案例. parent允许访问继承的类,而self是对正在运行的方法(静态或其他)所属的类的引用.

If you are looking for the correct cases for their use. parent allows access to the inherited class, whereas self is a reference to the class the method running (static or otherwise) belongs to.

self关键字的一种流行用法是在PHP中使用Singleton模式时,self不支持子类,而static

A popular use of the self keyword is when using the Singleton pattern in PHP, self doesn't honour child classes, whereas static does New self vs. new static

parent提供了访问继承的类方法的功能,如果您需要保留一些默认功能,则通常很有用.

parent provides the ability to access the inherited class methods, often useful if you need to retain some default functionality.

这篇关于PHP:自我:: vs父母::带扩展的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆