2

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();
PeeHaa
  • 71,436
  • 58
  • 190
  • 262
user28490
  • 1,027
  • 8
  • 8
  • 1
    Take a look at this post: [http://stackoverflow.com/questions/4280001/protected-static-member-variables][1] [1]: http://stackoverflow.com/questions/4280001/protected-static-member-variables – Andras Toth Feb 28 '13 at 11:50
  • Awesome! I did not know that late static binding thing -- it is really useful :) – user28490 Feb 28 '13 at 11:56

3 Answers3

3

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.

SDC
  • 14,192
  • 2
  • 35
  • 48
  • Thank you sir I will accept yours as the answer as soon as my very tiny reputation allows me to do so :) – user28490 Feb 28 '13 at 11:55
1

Yes it overwrite it but in your case you did not overwriting getComment method of parent class.

if you try

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

then it will display I am B.

what actually you are doing is calling getComment method of b class which is not exists in child class so it bubble up to parent class method and display result.

Dipesh Parmar
  • 27,090
  • 8
  • 61
  • 90
  • But why does it work in an instance context, for ex: 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(); // echo I am B – user28490 Feb 28 '13 at 11:51
  • @user28490 look your tiny reputation has increase little...lol – Dipesh Parmar Feb 28 '13 at 12:02
0

You need to use LATE STATIC BINDING

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

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

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

I hope this make some sense

Aamir Mahmood
  • 2,704
  • 3
  • 27
  • 47