SESSION & Classes

I want to be able to stock data in $_SESSION[‘cart’].
But when I use this variable in a Class, it automatically become an Object.
I can’t understand how it work.

<?php class Cart{ public function __construct(){ if(!isset($_SESSION)){ session_start(); } if(!isset($_SESSION['cart'])){ $_SESSION['cart']=array(); } } } $cart=new Cart(); $_SESSION['cart'][0]="a"; array_push($_SESSION['cart'],'a'); ?>

But got this error : Fatal error: Cannot use object of type Panier as array in […]/test.php on line 13

I think your logic is a little backwards? If I were doing this I would stack the items in a plain old array and if I had to just dump it in $_SESSION.

Something like this:
[php]<?php
session_start();
class Cart {
/* Scope of array is private */
private $myCart = array();

public function setCart($item) {
	array_push($this->myCart, $item);
}

   /* If you accessed this Method (function) it would also become public */
public function getCart() {
	return $this->myCart;
}

public function displayArray() {
	echo '<pre>';
	print_r($this->myCart);
	echo '</pre>';
}

/* Scope of Array becomes public in $_SESSION['cart'] */
public function assignToSession() {
	$_SESSION['cart'] = $this->myCart;
}

}

$cart = new Cart();
$cart->setCart(‘Banana’);
$cart->displayArray();
$cart->setCart(‘Orange’);
$cart->setCart(‘Apple’);
$cart->displayArray();

$cart->assignToSession();

echo ‘

’;
print_r($_SESSION[‘cart’]);[/php]

In a practical working script the array ( or objects using a different kind of script ) would be most likely propagated by a database table (for example a MySQL database table).

Sponsor our Newsletter | Privacy Policy | Terms of Service