Thursday, 5 September 2013

php variable scope and fwrite inside function

php variable scope and fwrite inside function

I'm trying to figure out where my add to cart process is messing up, so i
decided to add in some logging code (fwrite) Well then I quickly learned
about php variable scope. And now I'm stuck.
The first thing i tried before i learned about variable scope.
$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);
So that returned an error saying something like fp is not defined.
Then i looked up php variable scope. Because if a similar thing were
written in another, it may have worked.
I tried declaring $fp global;
function addtocart($pid,$qty){
global $fp;
fwrite($fp, 'addtocart()\nProduct ID: '. $pid .'\nQuantity: '.
$qty .'\n');
I get the error "Warning: fwrite(): 3 is not a valid stream resource" like
its turning $fp into some sort of integer. Why?

No comments:

Post a Comment