Pass a PHP variable created in one function to another

I use wordpress and woocommerce (an e-commerce plugin) to set up a shopping cart. In my functions.php, I store the data in a variable as follows:

add_action( 'woocommerce_before_calculate_totals', 'add_custom_price' ); function add_custom_price( $cart_object ) { foreach ( $cart_object->cart_contents as $key => $value ) { $newVar = $value['data']->price; } } 

I need to be able to use $newVar in another function so that I can repeat the result in a different area of ​​the page. For example, if I had the following function, how would I use $newVar inside it?

 add_action( 'another_area', 'function_name' ); function function_name() { echo $newVar; } 

How can i do this?

+4
source share
5 answers

You can make a global variable:

 function add_custom_price( $cart_object ) { global $newVar; foreach ( $cart_object->cart_contents as $key => $value ) { $newVar = $value['data']->price; } } function function_name() { global $newVar; echo $newVar; } 

Or if $newVar already available in a global scope that you could do:

 function function_name($newVar) { echo $newVar; } // Add the hook add_action( 'another_area', 'function_name' ); // Trigger the hook with the $newVar; do_action('another_area', $newVar); 
+6
source

Any reason you can't call your function from a foreach loop?

 function add_custom_price( $cart_object ) { foreach ( $cart_object->cart_contents as $key => $value ) { $newVar = $value['data']->price; function_name($newVar); } } 
+4
source

You should use the return $ variable in your functions:

 function add_custom_price( $cart_object ) { foreach ( $cart_object->cart_contents as $key => $value ) { $newVar = $value['data']->price; } return $newVar; } function function_name($newVar) { //do something with $newVar } 

And use like this:

 $variable = add_custom_price( $cart_object ); $xxx = function_name($variable); 

UPDATE:

Looking at what @ChunkyBaconPlz said, $ newVar should be an array:

 function add_custom_price( $cart_object ) { foreach ( $cart_object->cart_contents as $key => $value ) { $newVar[] = $value['data']->price; } return $newVar; } 
+3
source

This is a problem with the area. First you need to create (create) $ newVar outside the function. Then it will be available for viewing by another function.

You see that the area determines which objects can be seen by other objects. If you create a variable inside a function, it can only be used inside that function. As soon as the function completes, this variable will be eliminated!

So, to fix it, literally just create "$ newVar" before you create the function, and you should be good to go.

0
source

even if its defined global does not work when calling another function, however, if we call a function in another function, it works.

 <?php function one() { global $newVar; $newVar = "hello"; } function two() { one(); global $newVar; echo $newVar; } two(); ?> 
0
source

Source: https://habr.com/ru/post/1499670/


All Articles