Trying to update the global value from a hooked function

Links for php scripts

Moderators: egami, macek, gesf

Post Reply
jobanana
New php-forum User
New php-forum User
Posts: 3
Joined: Mon Jan 08, 2018 2:55 am

Thu Jan 18, 2018 4:36 pm

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: Select all

$xyz; 
In a functions file, I have put:

Code: Select all

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?

User avatar
hyper
php-forum Fan User
php-forum Fan User
Posts: 687
Joined: Mon Feb 22, 2016 5:52 pm

Fri Jan 19, 2018 12:36 pm

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: Select all

<?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.

Post Reply