views:

1198

answers:

2

Hi there, I have a quick question, first one too!

How is it possible to serialize sub-objects to $_SESSION? Here.

<?php // this is "arraytest.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';}
}

?>

<?php // this is page 1
require_once('arraytest.php');
session_start();
$bob = new dododo();
$_SESSION['bob'] = serialize($bob);
?>

<?php // this is page 2
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 affected to "poop" doesn't exist no more. Fatal error: Call to a member function getarray() on a non-object in on line 6

+2  A: 

Your problem isn't serialization. Class dododo's constructor has a bug. You aren't referencing the class object, but instead are referring to a new variable "poop" inside of the constructor's namespace. You're missing a $this->.

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

It works fine with this change.

Frank Crook
Thanks alot! Will slap myself on wrist for "this". This is me, not being proud of my mistake. -_-
MrZombie
A: 

It has got nothing to do with serialization. It doesn't exist in the first place. You've got it wrong in the constructor, should be:

   public function __construct(){
        $this->poop = new arraytest();
    }
vartec
Thanks to you too. Won't do that mistake again.
MrZombie

related questions