0

我试图弄清楚我的添加到购物车过程在哪里搞砸了,所以我决定添加一些日志记录代码(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 变成某种整数一样。为什么?

4

4 回答 4

1

尝试在函数内部使用 fopen ......我认为这是最好的解决方案,也许让代码为每个函数创建不同的日志记录文件。

希望这会有所帮助。

于 2013-09-05T15:18:58.640 回答
1

你可以试试这样的

<?php 
$pid=$_SESSION['PID'];
$qty=$_SESSION['QTY'];
$contentToWrite="Product ID:". $pid ."Quantity:". $qty;
$writeToText = "filePathToWriteTo.php";

if (is_writable($writeToText)) {


    if (!$willWrite = fopen($writeToText, 'w')) {
         echo "writeToText Cannot open file ";
         exit;
    }


    if (fwrite($willWrite, $contentToWrite) === FALSE) {
        echo "writeToText Cannot write to this file ".$writeToText;
        exit;
    }
    fclose($willWrite);

} else {
    echo "May be security reasons ".$writeToText." is not writable";
}?>
于 2013-09-05T15:26:56.233 回答
0

您需要将文件处理程序传递给函数

function addtocart($fp,$pid,$qty){
// your code
}

根据您的代码,这是最简单的方法,并且比使用 $GLOBALS 好得多。

您是否使用http://php.net/manual/es/function.error-reporting.php来显示错误,或者您可以查看 Web 服务器的错误日志。

于 2013-09-05T15:16:10.520 回答
0

一个更好的方法是使用 $GLOBALS[] 数组。

我不确定是否可以将 global-keyword 用于资源。

于 2013-09-05T15:16:30.030 回答