繁体   English   中英

在PHP函数外部设置和使用变量

[英]Set and use variable outside of function in PHP

我有一个函数,可通过SOAP API将销售信息传递给第三方服务,并返回包含结果的数组。

我需要从该数组中获取特定键,将set作为变量使用,或以其他方式在该函数之外使用它。

我在函数中声明变量,如下所示:

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

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

这是我需要使用此变量的语句,每次都会失败:

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;
        }
    }
}

我对此并不陌生,因此不胜感激。

更正了输入错误,在生产代码中变量名是正确的。

使用以下代码:

$mbStatus更改$mbStatus $status

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;
        }
    }
}

您可以返回变量,并按如下方式使用它:

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

...
$status = $checkoutShoppingCartRequest['Result']['Status'];
return $status;
}

$status = foo();

然后检查。

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

看起来您想从该函数返回status并在外部使用它。

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

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

    //for loop here
}

避免使用global global是邪恶的。

在全局范围内的函数外声明$status

$status = ''; // Global scope

function foo() {
    global $status; // Access the global $status var
    $status = 'status set in function';
}

foo();
print_r($status); // Outputs "status set in funciton"

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM