What is the difference between self::$bar and stat

2019-01-13 00:28发布

Possible Duplicate:
New self vs. new static

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();

produces

1234
1234

2条回答
Explosion°爆炸
2楼-- · 2019-01-13 00:44

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.

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;
}

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

In the above scenario, using static instead of self will result in Bar::$bar being used instead of Foo::$bar, because the interpreter then takes into account the redeclaration within the Bar class.

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

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

查看更多
The star\"
3楼-- · 2019-01-13 00:59
self - refers to the same class whose method the new operation takes place in.

static - in PHP 5.3's late static binding refers to whatever class in the hierarchy which you call the method on.

In the following example (see get_called_class()), class B inherits both methods from class A. Self is bound to A because it's defined in A's implementation of the method, whereas static is bound to the called class despite the fact that it's also in A's implementation of the method.

class A {
    public static function get_A() {
        return new self();
    }

    public static function get_me() {
        return new static();
    }
}

class B extends A {}

echo get_class(B::get_A());  // A
echo get_class(B::get_me()); // B
echo get_class(A::get_me()); // A
查看更多
登录 后发表回答