Skip to content

Nit/trivial: Fix Anonymous functions Example # 4 cart "add" method to support adding quantity to an existing product - #5949

Open
willy-b wants to merge 1 commit into
php:masterfrom
willy-b:fix-add-method-of-checkout-example-to-support-adding-the-same-product-multiple-times
Open

willy-b wants to merge 1 commit into
php:masterfrom
willy-b:fix-add-method-of-checkout-example-to-support-adding-the-same-product-multiple-times

Conversation

@willy-b

@willy-b willy-b commented Oct 14, 2026

Copy link
Copy Markdown
Contributor

Nit/trivial - feel free to ignore or accept, figured I'd share in case you are interested to take the update.

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 was 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 by a strange add method from the point of the example which is the getTotal method.

…ng 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.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant