php 5.3+
Sorry for the long question, but I want to learn this completely.
I know I can't call a non-static same class method from inside a static method, without the class being instantiated as an object.
class Person
{
private $people_array;
function data_all_get()
{ // touch database, return array of people
$this->people_array = // etc dbquery results
}
static function showPeople()
{ // call class method
$people_data = $this->data_all_get();
// Fatal error: Using $this when not in object context
}
} // end class Person
From searching on SO, I found some interesting approaches, but wondering how each approach affects the code environment.
My questions are below:
I could instantiate the class as an object inside the static method, to gain access to the non-static method
static function showPeople()
{ // instantiate as object
$person = New Person();
// call class method
$people_data = $this->data_all_get();
}
Q1 - what problems could this cause ? in my situation, the class does not have a constructor so no other class methods nor vars would be affected by the instance. Would this new object just take up a little space in memory during script execution? Doesn't seem too bad...
the other option would be to convert the "data_all_get" method into a static method, so it could be called from inside the static method "showPeople", i.e.
self::showPeople()
the "data_all_get" method is being used by other methods in the class when it is instantiated as an object, to set the value of the private var, to reduce trips to the database, if it is already set. I know this probably could be part of a constructor function, but I never have a need for this "Person" object to be instatiated more than once per php script request, the class is mostly used to group functions and vars together for organization ...
Q2 - what are the implications of making "data_all_get" into a static method ? are there any? if the method was static, but it sets the value of the private var $people_array (which is not static), I think that var would be able to be updated or overwritten if the object ever needed to be instantiated a second time in a single script request, correct? Plus since the property is not static other methods of the class can access it.
Q3 - Could I call the static method "data_all_get" as many times as I wanted without "breaking anything" (a loaded question IK).
Q4 - Does it simply use additional memory every time the static method is called?
Thank you