0

The code is here:

class A {
    public static $property = 1;

    public function test(){
       echo self::$property;
   }
}

class B extends A{
    public static $property = 2;
}
$b = new B();

echo $b->test() . "\n";

Console log:

$:1

I know that the class B has overwrite the static property.

What is the cause of this result?

VictoryForYou
  • 65
  • 2
  • 8

2 Answers2

1

When you have added

`echo self::$property;` 

to test() of A whether you overwrite the value of static variable in extended class or not it will refer to the parent class value but when your change this to

`echo static::$property;` 

it will give the value based on the class object.more info here

Try this: DEMO

Community
  • 1
  • 1
Suchit kumar
  • 11,809
  • 3
  • 22
  • 44
0
  • self is the same as $this for static methods/variables but always acts on the defining class.
  • static is the same as $this for static methods/varialbes but always acts on the calling class (this is known as late static binding which is a relatively new feature of php

Source: Read article

If you want to echo the value from the class you made the object of, you can use use the below,

class A {
    public static $property = 1;

    public function test(){
       echo static::$property; // changed self to static
    }
}

Hope you understood! Thanks.

masterFly
  • 1,072
  • 12
  • 24