Php class variables

I have a class called MyCart.

Class MyCartClass
{
var $MyCart;  

function getCart(){
  return $this->MyCart;
}

function addItem($item){

    if ($this->MyCart){
        $this->MyCart .= ','.$item;
    } 
    else{
        $this->MyCart = $item;
    }

}

};

$globalCart = new MyCartClass; // create an instance of the class

A variable "$MyCart"is a string containing all the items in the basket, separated by a comma.

Now I save this class in a file with the name "cart.php"and include it in another file.

HOWEVER, every time I call a function "addItem", the if statement goes to the else branch, which means that the variable "$MyCart"does not contain the current state of the basket.

Do I need to store the state of my basket in the "session" variable? Because it will be available from all files for sure ..

I would be grateful for any help!

Thank.

+3
source share
4 answers

If you want to keep it between requests, then yes, you need to put it in $ _SESSION.

$globalCart $myCart var.

+2

. .

$items

class Cart {

    function __construct() {
        $this->items = array();
    }

    function add($item) {
        $this->items[] = $item;
    }

    function save() {
        $SESSION["cart"] = $this->items;
    }

    function get_items_string() {
        return join(",", $this->items);
    }

}

PHP , .

+5

, :

Class MyCartClass { 
    var $MyCart = array();

    public function __construct(){
        $this->MyCart = deserialize($_SESSION['CART']);
    }

    public function __destruct(){
        $_SESSION['CART'] = serialize($this->MyCart);
    }


    function getCart(){
        return $this->MyCart;
    }

    function addItem($item){
        $this->MyCart[] = $item;   
    }
}

, , .: -)

+1

yours can even serialize the entire class into $ _SESSION [] ... but in general, it’s a good idea to save some id in the session - as an example of a user ID and save all other data in mysql. Getting it every time is necessary ...

0
source

All Articles