-1
<?php
class A{
    static $var;

    function test(){
      var_dump(self::$var);
    }
}

class B extends A{
    static $var = 'something';
}

$b = new B();
$b->test();
?>

why does this print out null and how do I fix this? It works if I do not set $var as static but i need it to be accesible without creating an instance.

M. Eriksson
  • 13,450
  • 4
  • 29
  • 40
J. Doe
  • 54
  • 1
  • 8
  • 3
    This is where `static` vs `self` comes in to play. If you change it to `var_dump(static::$var)`, it will you the property in the child class instead. Example: https://3v4l.org/oviE9 – M. Eriksson May 23 '18 at 13:26

1 Answers1

-1

$b->test(); prints null because it is null. When you do this:

class B extends A{
    static $var = 'something';
  }

you're not actually doing anything to the $var property in your A class. The property is defined with the static keyword, and per the docs, "A property declared as static cannot be accessed with an instantiated class object (though a static method can)." Thus you cannot inherit it (or subsequently set it) from your B class.

If you want the test() method to output anything meaningful, you need to set it statically, such as:

 A::$var = "something";
WillardSolutions
  • 2,316
  • 4
  • 28
  • 38
  • *"you cannot inherit [static properties]"* – Wrong: https://3v4l.org/GotZ4. You got the issue rather backwards. – deceze May 23 '18 at 13:28