Skip to content
Advertisement

Static counter of subclass instances in PHP

I’m aware of a pattern for adding a static counter to a class to count the number of instances of that class

JavaScript

What I would like to do is to add a couple of subclasses to Vehicle and count instances of those independently

JavaScript

So calling Bike::getCount() and Car::getCount() would get the count of the number of Bikes and Cars respectively

Is this possible without

  • repeating code in the subclasses?
  • setting up some kind of counting array keyed by class name in the superclass?

Advertisement

Answer

A lot depends on where you define the count and how you access it. If you have 1 count in the base class, then there is only 1 count. If you have a count in each class, then you need to be aware of how to access the right value. Using self or static is discussed more What is the difference between self::$bar and static::$bar in PHP?

JavaScript

This has both, and in the constructor, it increments them both. This means there is a total of all vehicles and of each type…

JavaScript

gives (not very clear though)…

JavaScript
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement