PHP Globals变量

时间:2017-08-09 18:38:51

标签: php global-variables

我知道全局变量不建议使用,但在我的情况下,我没有其他选择。我想将一些数据存储在全局变量中,以便以后在同一个脚本中使用。这是我的代码:

<?php
if(isset($_POST['details_submit'])){
    $body = json_decode(file_get_contents('php://input'),true);

    $GLOBALS['details'] = "";
    foreach ($body as $key => $value) {
        $details.= "Item : ".$value['item_name'];
        $details.= ", Quantity : ".$value['quantity'];
        $details.= ", Amount : ".$value['amount'];
        $details.= ", Total : ".$value['total']."\n";
    }
    echo $details;

    $GLOBALS['subtotal'] = 0;
    foreach ($body as $key => $value) {
        $subtotal = $value['total'] + $subtotal;
    }
    echo $subtotal;
}// end if statement

if(isset($_POST['customer_submit'])){
    $customer = "";
    $customer.= "Customer : ".$_POST['Name']."\n";
    $customer.= "Email : ".$_POST['Email']."\n";
    $customer.= "Phone Number : ".$_POST['Phone']."\n";
    $customer.= "Residence : ".$_POST['Area'];
    echo $customer;

    $email = $_POST['Email'];

    $to    = 'example@gmail.com';
    $subject = 'Natures Touch Order';
    $message = "<b>Customer Order</b> \n"
                   .$details."\n
                <b>Customer Details</b> \n"
                   .$customer."\n
                 The subtotal is KSH ".$subtotal.".";

    $headers = 'From: '.$email."\r\n";
          'X-Mailer: PHP/' . phpversion();
    $send1 = mail($to, $subject, $message, $headers);
}
?>

全局变量为detailssubtotal,如我的代码所示。我使用全局变量的原因是因为我有两个不同的if语句,并希望在第二个if语句的第一个if语句中使用一些结果。一切都运作良好但是当发送邮件时我得到Undefined variable details and subtotal错误。可能是第一个if语句运行时数据没有存储在变量中?或者可能是什么问题??

1 个答案:

答案 0 :(得分:0)

在代码开头定义变量

<?php
    $a = 0;
?>

并指定一个值,然后在代码中进一步需要时更改该值。

文档:http://php.net/manual/en/language.variables.scope.php