...

View Full Version : function in class is undefined: OOP help needed



surreal5335
12-08-2010, 08:41 PM
I am building shopping cart class for my website and currently my addItems() function is undefined. Here is the code the function:



class shoppingCart
{
protected $items = array();

// adds $product_id to $items array()
public function AddItems($product_id)
{
if(array_key_exists($product_id, $this->items))
{
$this->items[$product_id] = $this->items[$products_id] + 1;
}
else
{
$this->items[$product_id] = 1;
}
}
}


Here is the code that is calling it:


// get_shopping_cart() is found in functions.php
// get_shopping_cart() creates a new shoppingCart() object
$shopping_cart = get_shopping_cart();

if(product_exists($product_id, $layout))
{
$shopping_cart->AddItems($product_id);
//echo 'product exits';
}


Here is the link to the page displaying the error I am getting:
http://paperlesswasp.com/millionaire/add_to_cart.php?id=01/marketing


Thanks a lot for the help

MattF
12-08-2010, 08:49 PM
$shopping_cart = new get_shopping_cart();

surreal5335
12-08-2010, 10:06 PM
Sorry about that, here is the code for get_shopping_cart();



// returns a shoppingCart() object
// function called in add_to_cart.php
function get_shopping_cart()
{
// $_SESSION is a means for working with cookies
// shopping carts hold temporary data with cookies
if(!isset($_SESSION['cart']))
{
// creates new shoppingCart() object from classes/shoppingCart.php
return new shoppingCart();
}
else
{
// unserialize essentially "unzips" an object from memory for use
return unserialize($_SESSION['cart']);
}
}

Fou-Lu
12-08-2010, 10:21 PM
Is the shoppingCart class file included within the functions.php file? If not, its likely reconstruction an (sorry its been awhile here so I'm kinda fudging this one) PHP_INCOMPLETE_CLASS. I believe this actually shows as its name, so you could confirm if this is the case here:


$shopping_cart = get_shopping_cart();
var_dump($shopping_cart);


That must show that its an object of type ShoppingCart. PHP does not allow you to cast, so if its failing its likely because it considers it incomplete and rolls it down to a stdclass object (which won't include the methods).
Check that out, if thats the case simply include the shoppingcart definition file where the unserialize for the session data is occurring.

surreal5335
12-09-2010, 03:47 AM
Ok, I figured it out... The class file was already included and var_dump() confirmed that $shopping_cart was infact an object of shoppingCart class.

It had to do with the AddItems() function in the class... stupid typo.

One of my $product_id vars was typed out as $products_id... got rid of the 's' and all is good.

Thanks for the help



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum