Question

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()
    {
        static::$count++;
    }
    public static function getCount()
    {
        return static::$count;
    }
}

class FirstChild extends ParentClass
{

}
class SecondChild extends ParentClass
{

}

And I use it just like this

FirstChild::inc();
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 $count not integer but array. And do sort of such things in inc and getCount methods:

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

and

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.

Was it helpful?

Solution

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.

OTHER TIPS

I think for what you're trying to do, having just an interface method (such as getCount()) in the abstract class and the counter in the derivate class, your first choice, is the least worst option. It doesn't make sense to have abstract static count in the parent class if you're not counting all instances for that count.

In general, I think the whole idea is a bit ugly, thus implementations would be ugly, too :)

You can declare protected static $count=0; for each child class, that way it will be unique for each child class but common for all instances of the classes. That is the most elegant solution to his problem.

abstract class ParentClass
{
    public static function inc()
    {
        static::$count++;
    }
    public static function getCount()
    {
        return static::$count;
    }
}

class FirstChild extends ParentClass
{
    protected static $count=0;
}
class SecondChild extends ParentClass
{
    protected static $count=0;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top