开发者

Php Session Object Interaction

开发者 https://www.devze.com 2023-03-30 08:52 出处:网络
I ask you for advice. I struggle with session/object interactions.... <?php class ShoppingCart { public $products

I ask you for advice. I struggle with session/object interactions....

<?php
class ShoppingCart 
{

    public $products 

    public function __construct($session) {
        $this->products = $session['products']; 
    }

    public addProduct($id) {
        $this->products[] = new Product($id);
        $_SESSION['products'] = $this->products;
    }

}

session_start();
$shoppingCart = new ShoppingCart($_SESSION); 
$shoppingCart->addProduct(1);
?>

How would you write similar code? It's only the stub but I don't like my addProduct method and all 开发者_开发问答this code in general. Please don't be critical and help me improve it. Maybe there are some design patterns or examples of such interaction?


class ShoppingCart {

    private $products = array();

    public function __construct() {
        if (isset($_SESSION['products'])) {
            $this->products = &$_SESSION['products']; 
        }
    }

    public addProduct($id) {
        $this->products[] = new Product($id);
    }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消