PHP: self::vs parent::with 扩展

标签 php class static parent self

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

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() 之间有什么区别吗?如果有,那是什么?

谢谢

问候

最佳答案

                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 是对运行方法(静态或其他方式)所属类的引用。

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

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

关于PHP: self::vs parent::with 扩展,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20886911/

相关文章:

c++ - 对静态整数数组的 undefined reference

jquery - 添加滚动页面底部的类

javascript - AJAX .post 方法不将数据传递给 PHP 脚本

php - 如何从表中获取数据,以日期为键并对应数据?

PHP date() 与时区?

python - 如何从父类方法中调用子类方法?

jQuery 禁用类上的复选框

C++ 静态局部函数与全局函数

c++ - 当我们可以使用普通函数修改静态数据成员时,静态成员函数的需求是什么?

php - 在显示不同的所有国家/地区后,如何显示一个国家/地区在我的数据库中出现的次数?