我试图弄清楚我的添加到购物车过程在哪里搞砸了,所以我决定添加一些日志记录代码(fwrite)然后我很快就了解了 php 变量范围。现在我被困住了。
在我了解变量范围之前我尝试的第一件事。
$fp = fopen('logs/functions.txt', 'w');
function addtocart($pid,$qty){
fwrite($fp, 'addtocart()\nProduct ID: '. $pid .'\nQuantity: '. $qty .'\n');
if($pid<1 or $qty<1) return;
if(is_array($_SESSION['cart'])){
if(product_exists($pid)) return;
$max=count($_SESSION['cart']);
$_SESSION['cart'][$max]['productid']=$pid;
$_SESSION['cart'][$max]['qty']=$qty;
}else{
$_SESSION['cart']=array();
$_SESSION['cart'][0]['productid']=$pid;
$_SESSION['cart'][0]['qty']=$qty;
}
}
fclose($fp);
所以返回了一个错误,说没有定义像 fp 这样的东西。
然后我查找了 php 变量范围。因为如果类似的东西写在另一个中,它可能会奏效。
我尝试声明 $fp global;
function addtocart($pid,$qty){
global $fp;
fwrite($fp, 'addtocart()\nProduct ID: '. $pid .'\nQuantity: '. $qty .'\n');
我收到错误“警告:fwrite():3 不是有效的流资源”,就像它把 $fp 变成某种整数一样。为什么?