Recursion in PHP Object $Price->setProduct($Product); $Product->setPrice($Price);
So.. I'm wondering what effect this has
$Price->setProduct($Product);
$Product->setPrice($Price);
echo $Product->getPrice()开发者_JAVA技巧->getTotal();
it shows RECURSION if i print_r($Product)
You've set two objects with references to each other. As a result, when you try to print_r one of them, you end up with recursion because the objects are continuously referencing back to each other.
This is what for example your Product object would look like:
Product
| Price
| Product
| Price
| Product
| Price
...and so on, because each Product can access a reference to Price, which can in turn access a reference to Product and it just keeps on going.
The application could be better designed by setting a reference to Price in the Product object. If you think about it logically in context of your example, the Price does not need to know information about Product. To exemplify, the Price of a Book would most likely need to be able to have methods that allow the price to be set, the price to be accessed, and or get the tax. None of the methods in the Price object would need to access anything from Product. However once you have a Product object, you would most likely need to know information about the Product like the Price.
精彩评论