It seemed to me that I was proposing an alternative solution that slightly changes your design, but does not require static definitions in each subclass. Depending on your use, this may or may not be a better option than the first solution.
This solution uses get_class() to find the type of object that we store, and then save it in the parent class - in the submatrix associated with the class name:
abstract class Article { public static $articles = array(); public function add_Object_To_Array() {
The above code does not use late static binding, so it will work with any version of PHP, and not just with PHP 5.3+.
When you run this version with the original example, you get the following output:
Array ( [Report] => Array ( [0] => Report Object ( ) [1] => Report Object ( ) ) [Interview] => Array ( [0] => Interview Object ( ) [1] => Interview Object ( ) ) )
If you have PHP 5.3 or later, you can expand it even further and use get_called_class() to define getInstances() static (in the Article class), which works as follows:
public static function getInstances() { $class = get_called_class(); // return isset(self::$articles[$class]) ? self::$articles[$class] : array(); if (isset(self::$articles[$class])) { return self::$articles[$class]; } else { return array(); } }
Then you can call this method in your example as follows:
print_r(Report::getInstances()); print_r(Interview::getInstances());
source share