gamex Posted April 13, 2010 Share Posted April 13, 2010 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? Quote Link to comment https://forums.phpfreaks.com/topic/198410-recursive-references/ Share on other sites More sharing options...
ignace Posted April 13, 2010 Share Posted April 13, 2010 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; } } Quote Link to comment https://forums.phpfreaks.com/topic/198410-recursive-references/#findComment-1041137 Share on other sites More sharing options...
gamex Posted April 13, 2010 Author Share Posted April 13, 2010 Thanks ignace, I actually have code that looks almost identical to the code you posted, I just posted what I thought was necessary for the question. Quote Link to comment https://forums.phpfreaks.com/topic/198410-recursive-references/#findComment-1041143 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.