<?php
//EXAMPLE, PSEUDO CODE
class Cart{
protected $items = [];//array of id => [stuff]
public function __construct(){
$this->read();
}
//$attributes - IDK, maybe quantity or ... something...
public function add(int $id, array $attributes = []){
if(isset($this->items [$id])){
//@todo - do smth about it...
}
$this->items [$id][] = $attributes;
return $this;
}
public function read(){
//might change this later, to db and or serialization
$this->items = json_decode((isset($_SESSION['cart'])));
return $this;
}
public function write(){
//might change this later, to db and or serialization
$_SESSION['cart'] = json_encode($this->items);
return $this;
}
public function getItems(){
return $this->items;
}
}
///
//thing is you don't care HERE about internal implementaion. Which can be changed later.
$cart = new Cart();
$cart->add(17,['quantity' => 12]);
$cart->add(42,['quantity' => 99])->write();
var_dump($cart->getItems());
Warning: PHP Startup: Unable to load dynamic library 'sodium.so' (tried: /usr/lib/php/8.3.5/modules/sodium.so (libsodium.so.23: cannot open shared object file: No such file or directory), /usr/lib/php/8.3.5/modules/sodium.so.so (/usr/lib/php/8.3.5/modules/sodium.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0
array(2) {
[17]=>
array(1) {
[0]=>
array(1) {
["quantity"]=>
int(12)
}
}
[42]=>
array(1) {
[0]=>
array(1) {
["quantity"]=>
int(99)
}
}
}
Output for 5.6.0 - 5.6.40
Catchable fatal error: Argument 1 passed to Cart::add() must be an instance of int, integer given, called in /in/8A7Pv on line 41 and defined in /in/8A7Pv on line 13
Process exited with code 255.