NYCPHP Meetup

[nycphp-talk] Static variables, self:: and abstract classes

Andrew Kamm akamm at demicooper.com
Tue Jun 6 09:51:40 EDT 2006


Hello all -- I've coded a set of classes that inherit from an abstract
class. To my dismay, I've realized after charting and coding everything out
that my class hierarchy may be of no use because of how PHP handles
inheritance of variables/methods when extending a class.

In short, when a method is declared in the parent class and uses
"self::$whatever", when calling the method from a child class the "whatever"
portion always references the parent value of "whatever."

I've come to grips with this being just the way it is, but does anyone have
a solution that will prevent me from cutting and pasting all the methods
from my parent class into the child class (effectively killing the point of
the inheritance)?

In addition, is there any logical reason for the language to operate this
way? I found it reported as a bug on the PHP site, but I believe the final
result/response was that it's not a bug, but intentional. I don't know Java
or C, so I have no frame of reference, but it seems kind of weird to me.


Example:

*****************************************
abstract class ParentClass {
    protected static $myVar = "parent var!";
    function printVar() {
        echo self::$myVar;
    }
}  


class ChildClass extends ParentClass {
    protected static $myVar = "child var!";
}


ChildClass::printVar();  //displays "parent var!"
*****************************************


thanks in advance!


-- 
Andrew Kamm






More information about the talk mailing list