john zachos john zachos - 5 months ago 20
PHP Question

how to save many objects in a $session array variable

I'm new in the object oriented programming so this question might be silly...

I've created my class in a separate file called classProduct.php

<?php
class product{

public $prodId;
public $prodName;
public $prodPrice;

public function __construct($prodId,$prodName,$prodPrice){
$this->prodId = $prodId;
$this->prodName=$prodName;
$this->prodPrice=$prodPrice;
}

public function get_prodId(){
return $this->prodId;
}

public function get_prodName(){
return $this->prodName;
}

public function get_prodPrice(){
return $this->prodPrice;
}
}
?>


Then I tried to create a new object in a $_SESSION variable. This happens in another file called dailySales.php where I include the previous file using:

include_once("classProduct.php");


What I want to do is to save in
$_SESSION['myItems']
each new object. I am trying something like:

$newItem= new product($var,$var,$var);
$_SESSION['myItems']=array($newItem); // I believe here is where I do it wrong


Every time the buyer chooses one more products, the pages reloads (with ajax). When I
echo
or
var_dump
the
$_SESSION['myItems']
I only get the last object. What do I need to change to get it working correctly?

Of course I do need the object so I can easily remove a product from the shopping cart if
'Delete' is pressed.

Answer

This is working for me locally.

Define your items session variable as an array, then push them into the variable using array_push

class product {

  public $prodId;
  public $prodName;
  public $prodPrice;

  public function __construct($prodId, $prodName, $prodPrice) {
    $this->prodId    = $prodId;
    $this->prodName  = $prodName;
    $this->prodPrice = $prodPrice;
  }

  public function get_prodId() {
    return $this->prodId;
  }

  public function get_prodName() {
    return $this->prodName;
  }

  public function get_prodPrice() {
    return $this->prodPrice;
  }
}

Then use it like so:

$product = new product(1, "test", 23);
$product2 = new product(2, "test2", 43);

$_SESSION['items'] = array();
array_push($_SESSION['items'], $product, $product2);
echo '<pre>';
print_r($_SESSION['items']);
echo '</pre>';

This is the output of print_r()

Array
(
    [0] => product Object
        (
            [prodId] => 1
            [prodName] => test
            [prodPrice] => 23
        )
[1] => product Object
    (
        [prodId] => 2
        [prodName] => test2
        [prodPrice] => 43
    )

)
Comments