PHP object serialization and sessions

How can serialize sub-objects in $ _SESSION? Here is an example of what I'm trying:

arraytest.php:

<?php class ArrayTest { private $array1 = array(); public function __construct(){ $this->array1[] = 'poodle'; } public function getarray(){ return $this->array1; } } class DoDoDo { public $poop; public function __construct(){ $poop = new ArrayTest(); } public function foo() {echo 'bar';} } ?> 

Page 1:

 <?php require_once('arraytest.php'); session_start(); $bob = new DoDoDo(); $_SESSION['bob'] = serialize($bob); ?> 

Page 2:

 <?php require_once('arraytest.php'); session_start(); $bob = unserialize($_SESSION['bob']); $bob->foo(); print_r($bob->poop->getarray()); // This generates an error. ?> 

Somehow, when I deserialize the object, the ArrayTest instance assigned to the $poop object on page 1 no longer exists, as evidenced by the fact that page 2 generates a fatal error in the marked line:

Fatal error: call getarray () member function for non-object on line 6

+4
source share
2 answers

Your problem is not serialization. The constructor of the dododo class has an error. You are not referring to a class object, but instead referring to a new variable called "poop" inside the constructor namespace. You are missing $ this →.

 class dododo{ public $poop; public function __construct(){ $this->poop = new arraytest(); } public function foo() {echo 'bar';} } 

It works great with this change.

+7
source

It has nothing to do with serialization. It does not exist in the first place. You are mistaken in the constructor, it should be:

  public function __construct(){ $this->poop = new arraytest(); } 
+2
source

All Articles