Jump to content

[SOLVED] Store Data for Function


ciber

Recommended Posts

i have a function which request data from the YouTube API - here is my code, perhaps this can explain why

 

 

function stats($id,$type) {
$data = getdata($id);

if ($type == '1') {
  preg_match_all( "<yt:statistics viewCount='(.*?)' favoriteCount='(.*?)'/>", 
  $data, $stat);
  $final = $stat[1][0];
}

if ($type == '2') {
  preg_match_all( "<yt:statistics viewCount='(.*?)' favoriteCount='(.*?)'/>", 
  $data, $stat);
  $final = $stat[2][0];
}

return $final;
}

 

you see, my function does 2 things, so if I need to request it again, it will then download the data again

or will it hold it .. sorry im still new to this...

have the functions stat return all the stats for that $id as an array, so your script only calls stats() once per $id.

 

function stats($id) {
  $data = getdata($id);
  $stats = array();

  //Type 1
  if(preg_match_all( "<yt:statistics viewCount='(.*?)' favoriteCount='(.*?)'/>", $data, $stat)){
    $stats[1] = $stat[1][0];
  }

  //Type 2
  if(preg_match_all( "<yt:statistics viewCount='(.*?)' favoriteCount='(.*?)'/>", $data, $stat)){
    $stats[2] = $stat[2][0];
  }

  return $stats;
}

$stats = stats(123);
print $stats[1];
print $stats[2];

 

...or you could use OOP to make this more structured...do you know OOP?

no ... i only started to learn this about 3 months ago, and only in the last week have I really started to go into it a lot.

I am using the "dummy" way. :| still using the manual on php.net quite a bit.

 

 

The way you have changed this now, is much simpler! Thanks!!

np...the OOP way, you would create an instance using the $id. when the instance is created, you would do the API call, and store the $data into a variable inside that instance. then, you could call functions inside that instance which would do your preg_matchs on the $data.

 

OOP sounds scary (and it kind of is), but once you learn it, it's amazing!

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.