Jump to content

Recursive References


gamex

Recommended Posts

I have two classes, a Customer class, and a Cart class. Let me start by using a basic example:

 

class Customer {
     public $cart // Cart class
     public $shipping_address // Address class

     public function __construct(){
          $this->cart = new Cart();
          $this->cart->setCustomerReference($this);
     }
}

class Cart
     public $customer;

     public function setCustReference(Customer &$customer){
           $this->customer = $customer;
     }
}

 

I have functions in the cart class that calculates the order totals (subtotal, shipping, tax, etc), but in order to calculate tax, for example, I need to see the shipping address. I thought I would be able to pass a reference of the Customer class to the Cart when the cart is initialized.

 

It works the way I expected, but when I call print_r on the original Customer class (not the reference) from my code, in the output it says "[cart] => Cart Object ([customer:public] => Customer Object *RECURSION*)". Is this the wrong way for me to implement this? Is there a better way, or is that recursion message just letting me know for printing to the browser reasons?

 

Link to comment
Share on other sites

1. objects are always passed by reference

2. You may want to try:

 

class Cart {
    private $items = array();
    
    public function getSubtotal() {
        $subtotal = 0;
        foreach ($this->items as $item)
            $subtotal += $item->getSubtotal();
        return $subtotal;
    }
    
    public function getTotal() {
        return $this->getSubtotal();//calculate tax, deduction for coupon code, ..
    }
}

class CartItem {
    private $product = null;
    private $quantity = 0;
    
    public function __construct(Product $c, $quantity) {
        $this->product = $c;
        $this->quantity = $quantity;
    }
    
    public function getSubtotal() {
        return $this->product->getPrice() * $quantity;
    }
}

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.