4

How is it possible to serialize sub-objects to $_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 objects's $poop property in page 1 doesn't exist any more, as evidenced by the fact that page 2 generates a fatal error on the marked line:

Fatal error: Call to a member function getarray() on a non-object in on line 6

2
  • Tried to change them when I saw they weren't politically correct. Seems I failed. Will not do it again. Commented Apr 6, 2009 at 16:25
  • 1
    Exemplary sample code; clear, concise, just the sort of thing you look for when answering a question. I'm glad you weren't able to change the variable names. Commented Jan 20, 2013 at 19:31

2 Answers 2

7

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.

Sign up to request clarification or add additional context in comments.

1 Comment

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

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();
    }

1 Comment

Thanks to you too. Won't do that mistake again.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.