What is the best way in PHP
to do variable caching? For example, let's assume I have a table, with 4 rows.
name | job
--------------------------
Justin Smith | Plumber
Jack Sparrow | Carpenter
Justin Smith | Plumber
Katie White | Doctor
Which is built like:
foreach($people as $person) {
echo $person->name;
echo get_job($person->name);
}
And the function call get_job()
looks like:
function get_job($name) {
//This is pseudo code below
$row = MySQL->Query("SELECT job FROM people WHERE name = $name");
return $row->job;
}
As you can see, once we get the job of Justin Smith
, further down we shouldn't and don't need to do a full MySQL query again, since we know it is Plumber
.
I was thinking of doing a global variable which is a key=>value
array like:
global $jobs = array("Justin Smith" => "Plumber",
"Jack Sparrow" => "Carpenter",
"Katie White" => "Doctor");
Then in the get_job()
function I simply just check if the name exists in the array before querying. If not, insert the name and job into the array and return the job.
Basically, is there a better way to do this that is more elegant?