PHP中的self :: $ bar和static :: $ bar有什么区别? [英] What is the difference between self::$bar and static::$bar in PHP?

查看:93
本文介绍了PHP中的self :: $ bar和static :: $ bar有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在下面的示例中,使用selfstatic有什么区别?

What is the difference between using self and static in the example below?

class Foo
{
    protected static $bar = 1234;

    public static function instance()
    {
        echo self::$bar;
        echo "\n";
        echo static::$bar;
    }

}

Foo::instance();

产生

1234
1234

推荐答案

使用self引用类成员时,即表示您在其中使用关键字的类.在这种情况下,您的Foo类定义了一个受保护的静态属性,称为$bar.当您在Foo类中使用self来引用该属性时,您所引用的是同一类.

When you use self to refer to a class member, you're referring to the class within which you use the keyword. In this case, your Foo class defines a protected static property called $bar. When you use self in the Foo class to refer to the property, you're referencing the same class.

因此,如果您尝试在Foo类中的其他位置使用self::$bar,但是您有一个Bar类,其属性值不同,则它将使用Foo::$bar而不是Bar::$bar,这可能不会就是你想要的:

Therefore if you tried to use self::$bar elsewhere in your Foo class but you had a Bar class with a different value for the property, it would use Foo::$bar instead of Bar::$bar, which may not be what you intend:

class Foo
{
    protected static $bar = 1234;
}

class Bar extends Foo
{
    protected static $bar = 4321;
}

当您通过static 调用方法时,您正在调用名为

When you call a method via static, you're invoking a feature called late static bindings (introduced in PHP 5.3).

在上述情况下,使用self将导致Foo::$bar(1234). 使用static会导致Bar::$bar(4321),因为使用static时,解释器会在运行时考虑Bar类中的重新声明.

In the above scenario, using self will result in Foo::$bar(1234). And using static will result in Bar::$bar (4321) because with static, the interpreter takes takes into account the redeclaration within the Bar class during runtime.

您通常将后期静态绑定用于方法甚至类本身,而不是属性,因为您通常不会在子类中重新声明属性;可以在以下相关问题中找到使用static关键字调用后期绑定的构造函数的示例:

You typically use late static bindings for methods or even the class itself, rather than properties, as you don't often redeclare properties in subclasses; an example of using the static keyword for invoking a late-bound constructor can be found in this related question: New self vs. new static

但是,这并不排除将static与属性一起使用.

However, that doesn't preclude using static with properties as well.

这篇关于PHP中的self :: $ bar和static :: $ bar有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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