• Hello, I am fairly new to PHP and have been struggling with this for a long time. I would appreciate any help. I am trying to customize a plugin for my needs and pass a variable called $amount between two functions in my functions.php I would contact the owner of the plugin but he is very unresponsive. The problem is the second function isn’t getting the updated $amount that is created due to the if conditions. My understanding is that it is because it is a local variable. What is the best way to pass this variable? See the code below.

    function A( $run_this, $mycred, $request ) {
        if ( $run_this['ref'] == 'publishing_content' ) {
    
    		// Original amount (I will change this)
    		$amount =  $request['amount'];
    
             if(isset($_POST['term_id']))
          {
    		// If 74
    		if ($_POST['term_id'] == '74' ){
    			$amount = -50;
                    }
                  	// If 75
    		elseif ($_POST['term_id'] == '75' ){
    			$amount = -75;
                    }
    
                   // Re-add the new value (Amount gets updated. Good)
                    $run_this['amount'] = $amount;
          }
      }
                      return $run_this;
    }
    
    function B( $reply, $request, $mycred ) {
         if ( $reply === false ) return $reply;
    
         // I NEED THE NEW AMOUNT HERE. NOT ORIGINAL
           $amount =;
    
         return $reply;
    }
Viewing 2 replies - 1 through 2 (of 2 total)
  • Hello @learntodesign,
    the problem is the one you figured out, $amount is a local variable in both functions, so $amount in function A and $amount in function B are two different variables that are not accessible outside of the two functions.
    To share the value between them you have to put this declaration:
    global $amount;
    at the beginning of both function A and function B.
    Then you must be sure that function A is called before function B.
    But keep in mind that using global variables should be avoided because it creates hidden dependencies in your code (e.g. here you must remember that function A must be called before function B). It would be better that function A were explicitly called from function B.
    However if you can’t have a better structure for your code it’s fine, with the global declaration it will work.
    Another tip: the two functions should be named with a more explicative name.
    Giancarlo

    Thread Starter learntodesign

    (@learntodesign)

    Hi Giancarlo, thanks for the kind tip and reply. I wound up avoiding the use of global variables by simply reinstating the conditions for the amount in the second function as well. Thanks again

Viewing 2 replies - 1 through 2 (of 2 total)
  • The topic ‘Help with passing variable between functions’ is closed to new replies.