来自PHP脚本的变量影响Magento结账

I use the script below to set a flag when a product with a specific attribute is in the cart. My problem is that because I use this in the checkout I belive it conflicts with the other variables/arrays in the checkout and the grand total is double what it should be.

My question is how do I pass the flag out of this script without all the other variables effecting the rest of the checkout. I have tried unset($cart); thinking this would help but with no success!

(This code is placed at the top of my checkout.phtml file)

<?php

$collection = Mage::getModel('catalog/product')->getCollection();

$collection->addFieldToFilter(
    array(
       array('attribute'=> 'WWHAM','eq' => '1')
    )
);

$exemptProducts = array();
$exemptProductFound = false;

foreach ($collection as $product) {
$exemptProducts[] = $product->getId();
}

// now let's check if any are in the basket
$cart = new Mage_Checkout_Model_Cart();
$cart->init();

foreach ($cart->getItems() as $item) {
    if(in_array($item->getProductId(), $exemptProducts)) {
        // to make it simple, just set a flag
        $exemptProductFound = true;
    }
}
unset($cart);
?>

I'm not extremely familiar with cart, but instead of

$cart = new Mage_Checkout_Model_Cart();
$cart->init();

Try

Mage::getSingleton('checkout/cart')

First and foremost: You should almost never use 'new'. There's no real reason not to use Mage::getBlah.

Secondly, the issue may lie in your using Mage::getModel(), I think you need to use Mage::getSingleton().

The difference is that getModel will always give you a new object for that model while getSingleton will check to see if one already exists and return that instead. This means you're getting the properties of the existing cart object, which I think is the issue. Try that and we'll go from there.

EDIT: This answer digs into the Magento internals to show you the difference between the two.