Global variable

function statistics_exit() {
  global $user, $recent_activity;

i am a new learner of php, expect someone can explain it for me. why put the global keyword before the variable $user, $recent_activity. could i remove it? what’s the difference between have the global or haven’t the global before a variable .

Read This For More info and examples

For a quick answer, normally in PHP the scope of the variables is limited. So in your case the variables $user and $recent_activity should have declared outside the function and if you want to use them inside the function with their previous value then you should make them global before using. If you don’t put the keyword global then the line won’t have any meaning and will arise a error. Any variables declared inside a function will have the scope within that function only.

As suggested by kalon, go to the manual page for more details.

thanks rajug, if i make a ++ to the variable. do this will change the original variable’s value?

Will you please try once and see what will happen?

i have tried an example. the variable’s value is changed? if i want not change the original variable’s should i do?

Use common programing logic:

function statistics_exit() {
    global $user, $recent_activity;
    $newVar = $user; // use another variable
    $newVar++; // and increment.

I would rather suggest you by passing the variable to the function as parameter and use them if you don’t want to make effect in the original values:

$user = 2;
function statistics_exit($user) {
    $user++; // and increment.
// call the function and pass the variable to the function

thank you.