Search code examples
phpfunctionloopsvariablesnames

loop variable and function names php


Let's say that I have a php file. In it, I have some variables and some functions. For example:

$results = getResults($analytics, $profile);
printResults($results);

function getResults($analytics, $profileId) {
  return $analytics->data_ga->get(
       'ga:' . $profileId,
       '3daysAgo',
       '2daysAgo',
       'ga:sessions');
}

and

function printResults($results) {
  if (count($results->getRows()) > 0) {

    $profileName = $result->getProfileInfo()->getProfileName();

    $rows = $results->getRows();
    $sessions = $rows[0][0];

    // Print the results.
    print $sessions;
  } else {
    print "No results found.\n";
  }
}

Now, how could I loop through these, changing both variable and function names dynamically?

So (pseudocode, hope it is clear what it is trying to do)

for($i=2; $i<30; $i++){
    $results = $results$i = getResults$i($analytics, $profile);
    printResults$i($results$i);

    function getResults$i($analytics, $profileId){
    return $analytics->data_ga->get(
    'ga:' . $profileId,
    $i'daysAgo',
    ($i+1)'daysAgo,
    'ga:sessions');
    }
}

meaning that $results becomes $results2, $results3, etc and getResults() becomes getResults2(), getResults3(), etc and '3daysAgo' becomes 4daysAgo, 5daysAgo, etc.

Can it be done?


Solution

  • you can change variable name using this function:

       function get_var_name($var) {
            foreach($GLOBALS as $var_name => $value) {
                if ($value === $var) {
                    return $var_name;
                }
            }
    
            return false;
        }
    

    and if you want to change variable name $request with $request1 you can do:

    ${get_var_name($request).'1'} = $request;
    

    and if you want to create function dynamically:

      $function = create_function("/* comma separated arguments*/", "/*code as string*/);
    

    and call it:

    $function();