Search code examples
phpwordpressphp-5.3gravity-forms-plugin

Set and use variable outside of function in PHP


I have a function that passes sales information to a third-party service via a SOAP API, and returns an array with the results.

I need to take a specific key from that array, set is as a variable or somehow use it outside of that function in other code.

I'm declaring the variable in a function, like so:

function foo { 
...code to sell product through API...

global $status;
$status = $checkoutShoppingCartRequest['Result']['Status'];
}

And here is statement where I need to use this variable, which fails every time:

if ( $status !== "Success") {
    $validation_result['is_valid'] = false;

    foreach( $form['fields'] as &$field ) {
        if ( $field->id == '1' ) {
            $field->failed_validation = true;
            $field->validation_message = 'Your credit card could not be processed.';
            break;
        }
    }
}

I'm new to this so any help's appreciated.

Corrected typo, in production code variable names were correct.


Solution

  • You can return the variable and use it like -

    function foo() { 
    ...code to sell product through API...
    
    ...
    $status = $checkoutShoppingCartRequest['Result']['Status'];
    return $status;
    }
    
    $status = foo();
    

    Then check.

    if ($status !== 'Success') { .... }