0
votes

I am creating a cart bean object in php and then storing it in session how ever when i tried to access the array of object from the session it always return one bean object only Here is bean class

Class Cart{

private $quanity;
private $amount;

 function getQuantity() {
        return $this->quantity;
    }

    function getAmount() {
        return $this->amount;
    }

 function setQuantity($quantity) {
        $this->quantity = $quantity;
    }

    function setAmount($amount) {
        $this->amount = $amount;
    }

AddToCart.php

$c = new cart();
$c->setAmount("500");
$c->setQuantity("10");

if(isset($_SESSION["cartArray"])){

    $ar = $_SESSION["cartArray"];
    $ar[]=$c;
    $_SESSION["cartArray"]=$ar;

}
else{
    $c;
    $_SESSION['cartArray']= [];
    $_SESSION['cartArray'][]=$c;
}

orderHandler.php

$ar = $_SESSION["cartArray"];


foreach ($ar as $value) {
 echo '<pre>';
 print_r($value);
 echo '</pre>';

}

it gives me __PHP_Incomplete_Class Object and if try to write the following line in loop

$echo $value->getAmount();

error:

Fatal error: main(): The script tried to execute a method or access a property of an incomplete object. Please ensure that the class definition "cart" of the object you are trying to operate on was loaded before unserialize() gets called or provide a __autoload() function to load the class definition

1
You need to ensure that all Classes present in the session are loaded and available before you open the session. - RaggaMuffin-420

1 Answers

5
votes

The error message says it very clear: "Please ensure that the class definition "cart" of the object you are trying to operate on was loaded before unserialize() gets called".

What it fails to specify is that the function unserialize() is called behind the scene by the function session_start() to initialize the $_SESSION[] array.

You probably don't use an autoloader but manually include the needed files. If you were using an autoloader for your classes you wouldn't get the error in the first place.

The solution to your problem is quite simple: just make sure you include 'cart.php'; (the file that declares the class Cart) before calling session_start().