As you can see below I have a super class (Article) and two sub classes. I want each of the sub classes to have a static array that shall hold all it's objects.
abstract class Article
{
public static $articles = array(); // Variable for storing all the objects of each sub-class.
public function add_Object_To_Array()
{
array_push(self::$articles, $this);
}
}
class Report extends Article{}
class Interview extends Article{}
-Making two Report objects and adding them to their array:
$tmp = new Report();
$tmp->add_Object_To_Array();
$tmp = new Report();
$tmp->add_Object_To_Array();
-Making two Interview objects and adding them to their array:
$tmp = new Interview();
$tmp->add_Object_To_Array();
$tmp = new Interview();
$tmp->add_Object_To_Array();
print_r(Report::$articles);
print_r(Interview::$articles);
-The above script spits out the two arays:
Array
(
[0] => Report Object()
[1] => Report Object()
[2] => Interview Object()
[3] => Interview Object()
)
Array
(
[0] => Report Object()
[1] => Report Object()
[2] => Interview Object()
[3] => Interview Object()
)
Which looks pretty similar if you ask me, but the first one should only contain Reports, and the second one only Interviews.
1. It seems that there is only one array, why is it only one array?
2. I have a static container of objects in the same class, is this bad coding? (Any suggestions?)
I'm pretty new to php, but have a background from java.
abstract class Articleis missing its closing}.$thisin that context refers toabstract class Article. How will you push that on to the Array?$tmp = new Report(); $tmp->add_Object_To_Array();referred to the the "Report object's function"? (OOP thinking). I'm aware of the fact that there can be no objects of the abstract class .static::$articlesrather thanself::$articlesstatic::is required, but it's only part of the solution. You also need to define the variables separately.