Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/variables/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 为什么变量说未定义?_Php_Variables_Undefined - Fatal编程技术网

Php 为什么变量说未定义?

Php 为什么变量说未定义?,php,variables,undefined,Php,Variables,Undefined,这表示$total+=$sub未定义$total和$sub。$sub是在while循环中声明的,两个$sub都在函数中,因此它应该是一个局部变量。为什么我不能用它 public function cart() { foreach($_SESSION as $name=>$value){ if (substr($name, 0, 5) == 'cart_') { if((int)$value > 0){ $

这表示$total+=$sub未定义$total和$sub。$sub是在while循环中声明的,两个$sub都在函数中,因此它应该是一个局部变量。为什么我不能用它

public function cart() {
    foreach($_SESSION as $name=>$value){
        if (substr($name, 0, 5) == 'cart_') {
            if((int)$value > 0){
                $id = substr($name, 5, (strlen($name)-5));

                $st = $this->db->prepare("select id, name, price from deals where id=?");
                $st->bindParam(1, $id);
                $st->execute();

                while($cart_item = $st->fetch(PDO::FETCH_OBJ)){
                    $sub = $cart_item->price*$value;
                    echo $cart_item->name.' x '.$value.' @ '.$cart_item->price.' = '.$sub.' <a href="cart.php?add='.$id.'">[+]</a> <a href="cart.php?remove='.$id.'">[-]</a> <a href="cart.php?delete='.$id.'">[Delete]</a><br/>';
                }
            }
        }
        $total += $sub;
    }

}
公共功能购物车(){
foreach($\会话为$name=>$value){
如果(substr($name,0,5)=‘购物车’){
如果((int)$value>0){
$id=substr($name,5,(strlen($name)-5));
$st=$this->db->prepare(“从id=?”的交易中选择id、名称和价格”);
$st->bindParam(1,$id);
$st->execute();
而($cart_item=$st->fetch(PDO::fetch_OBJ)){
$sub=$cart\u item->price*$value;
echo$cart\u item->name.'x'.$value.@.$cart\u item->price.='.$sub.
; } } } $total+=$sub; } }
未定义的变量是$total,而不是$sub。添加$total=0;到函数顶部。

您从未初始化$total,因此出现错误。

如果

            $st = $this->db->prepare("select id, name, price from deals where id=?");
            $st->bindParam(1, $id);
            $st->execute();
返回0个结果

在每个之前定义
$sub
,为了安全起见,
$total
也要:

$sub = $total = 0;
foreach(...)

$total
变量应在
foreach
上方初始化。
$sub
变量应在顶部的
foreach
中初始化

$total = 0;
foreach ($_SESSION as $name => $value) {
    $sub = 0;
    ...

此外,您还可以移动
$total+=$sub更高,当
循环时位于内部
的正下方。

$sub在
$st->fetch(PDO::fetch_OBJ)
不返回任何项目时可能未定义