Search code examples
phplate-static-binding

Request for clarification about OOP procedure in PHP


I am trying to write the following code in PHP

class A {
 protected static $comment = "I am A" ;
 public static function getComment () {
  return self :: $comment; 
 }
}

class B extends A {
 protected static $comment = "I am B" ;
}

echo B::getComment () ; // echoes "I am A"

Shouldn't it return I am B ? In oop PHP does not the child overwrite the parent? Thank you for the clarifications.

== EDIT ==

Also my question is what is the difference then between static and instance because in instance it works:

class A {
    protected $comment = "I am A" ;

    public function getComment () {
        return $this -> comment ;
    }
}

class B extends A {
    protected $comment = "I am B" ;
}

$B=new B ;

echo $B->getComment();

Solution

  • The feature you're looking for is called "late static binding", and is documented here.

    The short version is that in order to get static variables working the way you want them to, you need to use static:: instead of self::.

    Note: this only works in PHP 5.3 and greater.