简体   繁体   English

If语句中的全局变量-PHP

[英]Global variables in If statements - PHP

I was looking for examples of using global variables in IF statements, found few but I still cannot make my code to work. 我一直在寻找在IF语句中使用全局变量的示例,虽然很少,但仍然无法使我的代码正常工作。 I'm declaring variable globally and tried to assign values inside if statement and later to check if the variable contains certain value. 我正在全局声明变量,并尝试在if语句内部分配值,然后再检查该变量是否包含某些值。 When I echo the variable, it is not updated with the value I'm assigning within if statement. 当我回显该变量时,不会使用我在if语句中分配的值对其进行更新。 My code: 我的代码:

<?php
    $cart = 0;

    if ((isset($_POST["b1"]) && $_POST["b1"] === "Add to cart")) { 
        global $cart; 
        $cart = 1;
        $query_HOD = "INSERT INTO orderLine 
                      (LINE_ID, PRODUCT_ID, QUANTITY, AMOUNT)
                      VALUES 
                      ('LINE1', '00001', 1, 6.99)";

        if ((isset($_POST["add"]) && $_POST["add"] === "Go to cart")) {
            echo $cart;
            if($cart === 1) {
                echo $cart;
                header("location:cart.php");
            }
            else {
                echo "<script type='text/javascript'>alert('Your cart is empty');</script>";
            }
        }
?>

isset methods are working fine, I have checked those, it seems to me that the variable is updated but only locally and does not affect the global variable. isset方法工作正常,我已经检查了这些方法,在我看来,变量是更新的,但仅在本地更新,不会影响全局变量。

Perhaps you're expecting a global variable to mean a variable that persists between requests; 也许您期望全局变量表示在请求之间持久存在的变量。 that's not what they are. 那不是他们。 A global is just a variable that is accessible anywhere in your code for that request . 全局变量只是可在该请求的代码中任何位置访问的变量。 As @user1231958 stated, you'll want a cookie or some other way to persist state. 如@ user1231958所述,您需要Cookie或其他某种方式来保持状态。

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

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