user28490
user28490

Reputation: 1037

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();

Upvotes: 2

Views: 71

Answers (3)

Aamir Mahmood
Aamir Mahmood

Reputation: 2724

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

Upvotes: 0

SDC
SDC

Reputation: 14212

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.

Upvotes: 3

Dipesh Parmar
Dipesh Parmar

Reputation: 27382

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.

Upvotes: 1

Related Questions