OOP PHP Get Total Quantity of Products Ordered

What is the best way using OOP PHP to find the total quantity of a shopping cart. The customer can have more than one item per page to add to the cart. So whenever the quantity of the cart changes I want the total to change. So I have a method in my cart class that will calculate the total quantity. Here is the method from my cart class.

 public function get_total_qty($total_qty = '')
    {
        $total_qty = 0;
        
        if (isset($_SESSION['cart']))
        {
           foreach($_SESSION['cart'] as $qty)
           {
              $total_qty = $total_qty + $qty;
           }
        }
        return $total_qty;
    }

Then I created an new object in the index and tried to get the quantities when they change so I can total them.

$total_qty = new Cart();
		
$total_qty->get_total_qty($cart_itm["qty"]);

$cart_itm[“qty”] is the variable that holds the quantity amounts.

all help greatly appreciated.

Well what I dont understand is why your Cart::get_total_qty() method accepts a parameter $total_qty, and then has it overwritten in the first line of your method body(by assigning $total_qty to 0). It seems that this parameter is redundant, since its overwritten immediately, it does not do anything at all. Would you mind elaborating?

Yes, That most certainly is a bug waiting to happen.

My guess is the intention was to provide a default value if none was passed. eg.
instead of

 public function get_total_qty($total_qty = '')
    {
        $total_qty = 0;

more like

 public function get_total_qty($total_qty = 0)
    {

Yeah, thats a possibility, and I guess only the OP can explain what exactly he meant.

Hi @Earl_Gile, before i go on with a bit refactored version of your code, I want say this:
OOP as a design is worth mastering. You need to really spend time on it, build on your knowledge base and just go out there and practice it. It all about object (not really :wink:) modelling the world as such: objects.

OK, so my refactored version of your code

NB: I had to create a wrapper class for the session, for fluency sake.

class Cart{

/** Initial accumulator value set to 0 */
private $totalQuantity = 0;

public function getTotalQuantity(){

	if($this->session->isset('cart'))
	{
		foreach($this->session->get('cart') as $item)
		{
			$this->totalQuantity += $this->totalQuantity;
		}

		return $this->totalQuantity;
	}
	throw new Exception('You have no session running. Log in to start buying.');
     }
    }

/** Session Wrapper Class 
*    Providing a fluent way to access and manipulate SESSION
*/
 class Session{

	private $session;

	public function __construct(){
		$this->session = $_SESSION
	}

	public isset($key){
		return isset($this->session[$key]);
	}

	public get($key){
		return $this->session[$key];
	}
}

Hope this helps. Let me know how well it goes.

Cheers!

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.