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
https://forums.phpfreaks.com/topic/198410-recursive-references/
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;
    }
}

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.