From a70ff51188c90ced39b40048f0bbb33d5414a61d Mon Sep 17 00:00:00 2001 From: William Bruns Date: Wed, 14 Oct 2026 23:47:39 +0000 Subject: [PATCH] Fix Anonymous functions Example # 4 cart "add" method to support adding quantity to an existing product At https://web.archive.org/web/20261014211813/https://www.php.net/manual/en/functions.anonymous.php#:~:text=add($product,%20$quantity) the add method of the shopping cart example is written: ``` public function add($product, $quantity) { $this->products[$product] = $quantity; } ``` The implementation does not match the name, and is more like "set", as if one called add twice for the same product it would not increment the quantity but replace with the value it was last called with, e.g.: ``` $my_cart->add('butter', 1); $my_cart->add('butter', 1); ``` would result in a quantity of 1 for butter instead of 2. This commit fixes that to avoid distraction from the point of the example which is the getTotal method. --- language/functions.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/language/functions.xml b/language/functions.xml index 5a8df8d6dc42..05d9241520cf 100644 --- a/language/functions.xml +++ b/language/functions.xml @@ -1258,7 +1258,7 @@ class Cart public function add($product, $quantity) { - $this->products[$product] = $quantity; + $this->products[$product] = (isset($this->products[$product]) ? $this->products[$product] : 0) + $quantity; } public function getQuantity($product)