Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass PHP variable created in one function to another

I am using wordpress and woocommerce ( an e-commerce plugin) to customize a shopping cart. Within my functions.php I am storing data in a variable like so:

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 a different function so I can echo the result on a different area of the page. For instance, if I had the following function, how would I use $newVar within it?

add_action( 'another_area', 'function_name' );

function function_name() {
    echo $newVar;
}

How can I do this?

like image 737
JCHASE11 Avatar asked Aug 29 '13 17:08

JCHASE11


People also ask

How can I pass variable from one function to another in PHP?

You need to instantiate (create) $newVar outside of the function first. Then it will be view-able by your other function. You see, scope determines what objects can be seen other objects. If you create a variable within a function, it will only be usable from within that function.

How do you assign a variable to another in PHP?

PHP Reference Assignment Operator In PHP, the reference assignment operator ( =& ) is used to create a new variable as an alias to an existing spot in memory. In other words, the reference assignment operator ( =& ) creates two variable names which point to the same value.

How can I transfer data from PHP to PHP?

Open your web browser and type your localhost address followed by '\form1. php'. Output: It will open your form like this, asked information will be passed to the PHP page linked with the form (action=”form2. php”) with the use of the POST method.


2 Answers

You could make the variable global:

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 is already available in the global scope 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);
like image 87
putvande Avatar answered Nov 07 '22 09:11

putvande


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

function add_custom_price( $cart_object ) {
    foreach ( $cart_object->cart_contents as $key => $value ) {
        $newVar = $value['data']->price;
        function_name($newVar);
    }
}
like image 36
ChunkyBaconPlz Avatar answered Nov 07 '22 10:11

ChunkyBaconPlz