2017-08-09 142 views
-2

我知道全局變量不建議使用,但在我的情況下,我沒有另一種選擇。我想將一些數據存儲在全局變量中,以便以後在同一個腳本中使用。這裏是我的代碼:PHP全局變量

<?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 = '[email protected]'; 
    $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

在php中的變量不是作用域的範圍。 –

+1

備註'$ headers'需要連接,而不是分號。 「X-Mailer:PHP /」。 phpversion()並不包含在你的頭文件中。 – Rasclatt

回答