Trying to update the global value from a hooked function

A

Anonymous

Guest
Hi,

Still new to PHP. I am having trouble with this. I want to hook into a specific place, and one thing I want to do there is update a global variable.

In my main php file, I have just put variable
Code:
$xyz;

In a functions file, I have put:

Code:
function save_xyz( $user_id ){
  
  global $xyz;
 
  if( !xyz ){
    $xyz = 1;
    return $xyz;
  }

  $xyz = 2;
  return $xyz;

}

add_action( "pmpro_after_checkout", "save_xyz" );

Theoretically, that should work shouldn't it?
 
In general using global variables means that there is a logic problem in your script: in your script you are returning a global variable, which makes no sense.

Code:
<?php

$xyz = 0;

function change_it ($variable) {
  $variable++;
  return $variable;
}

$xyz = change_it($xyz);

There are cases for using global variables, but very rarely, as the above code shows, it's quite simple to change a variable without having to use a global one.
 
Back
Top