开发者

php class variables

I have a class named 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

The variable "$MyCart" is a string containing all t开发者_JAVA百科he items in the cart, separated with a comma.

Now, I save this class to a file named "cart.php" and I include it in another file.

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

Do i need to store the state of my cart into a "session" variable? Cause this way it will be accessible from all files for sure..

I would appreciate any kind of help!

Thanks.


Don't use a string to store a list. It's just a bad idea all around.

Instead, store $items as an array, and define it in the constructor

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);
    }

}

My PHP is a little rusty, but that should get you started.


If you mean saving it between request then yes you need to put it in $_SESSION.

Otherwise within one request you can use your $globalCart and not lose the contents of your $myCart var.


To simplify this just store the data in an array and use serialize and deserialize to store the data:

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;   
    }
}

Please note I just wrote this quickly and didn't run it as I don't have access to run it right now. :-)


your can even serialise all class to $_SESSION[] ... but generally good idea is to store in session some id - as example user id & store all all other data in mysql. Getting it each time, is needed ...

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜