Ruslan Polutsygan Ruslan Polutsygan - 1 year ago 61
PHP Question

Late static binding in PHP, vars are being shared between child classes

Maybe my question has been asked several times, but...

I have the following code

abstract class ParentClass
protected static $count=0;
public static function inc()
public static function getCount()
return static::$count;

class FirstChild extends ParentClass

class SecondChild extends ParentClass


And I use it just like this

echo SecondChild::getCount();

It shows me "1". And as you probably guess I need "0" :)

I see two ways:

  1. Adding
    protected static $count=0;
    to each derivative classes

  2. Make
    not integer but array. And do sort of such things in



return static::$count[get_called_class()];

But I think these ways are a bit ugly. First - makes me copy/paste, what I'd like to avoid. Second - well, I don't know:) I just don't like it.

Is there a better way to achive what I want?

thanks in advance.

Jon Jon
Answer Source

No, you have exactly laid out the two most practical options to address this. PHP cannot work magic; when you declare a static protected property you get exactly that: one property. If the syntax you give did work that might be good news for everyone who needs to do that, but it would be absolutely horrible news for everyone else who expects PHP OOP to behave in a somewhat sane manner.

And for the record, if you don't need a separate counter for all derived classes without exception then I consider the explicit protected static $count = 0 in derived classes that do need one to be a beautiful solution: you want your own counter, you ask for one, and that fact remains written in the code for everyone to see.