Does a static keyword affect constants?

class A{ const FOO = 1; } class B extends A{ const FOO = 5; function foo(){ print self::FOO; print static::FOO; } } $b = new B; $b->foo(); 

He prints 5 in both cases.

So, is there no difference in using static vs self on constants?

+4
source share
3 answers

In the context of Late Static Binding, there is a difference.

Consider this code:

 <?php class A { const FOO = 1; function bar() { print self::FOO; print "\n"; print static::FOO; } } class B extends A { const FOO = 5; } $b = new B; $b->bar(); // 1 5 

If you run this code, the output will be:

 1 5 

When referring to self::FOO value 1 is output (although bar() is called in class B , but when using the static , later static binding is applied, and it refers to the FOO constant from B , not A when using the static keyword.

This is true for PHP 5.3 and later.

+3
source

In your example, it’s not enough to see the difference. However, if you have:

 class Foo { protected static $FooBar = 'Foo'; public function FooBar() { echo "static::\$FooBar = " . static::$FooBar . PHP_EOL; echo "self::\$FooBar = " . self::$FooBar . PHP_EOL; } } class Bar extends Foo { protected static $FooBar = 'Bar'; } $bar = new Bar(); $bar->FooBar(); 

You will see the difference (with scope and which instance will be resolved [inherited against the base])

self , parent and static keywords

+2
source

Yes, there is a difference. In your code example, both self and static refer to the same const FOO declaration.

The example sent by user "drew010" shows the difference.

+1
source

All Articles