Is it possible to unserialize a object with a func in it?

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
pivdet
Forum Newbie
Posts: 3
Joined: Sun Nov 02, 2008 9:24 pm

Is it possible to unserialize a object with a func in it?

Post by pivdet »

Hi, all
I wrote a simple php file like this:

Code: Select all

 
class A {
  function A($data) {
    $this->data = $data;
  }
 
  function printData() {
    print 'A thinks A data is ' . $this->data . "\n";
  }
}
 
 
$a = new A("origAdata");
print '<pre>';
$a->printData();
 
$serA = serialize($a);
echo "<br>" . $serA . "<br>";
 
Simply, it works like
O:1:"A":1:{s:4:"data";s:9:"origAdata";}
However, I wrote a second file:

Code: Select all

$newA = unserialize('O:1:"A":1:{s:4:"data";s:9:"origAdata";}');
$newA->data = 'newAdata';
$newA->printData();
 
This time it fails, I am wondering if I can unserialize a object with a func in it?
User avatar
John Cartwright
Site Admin
Posts: 11470
Joined: Tue Dec 23, 2003 2:10 am
Location: Toronto
Contact:

Re: Is it possible to unserialize a object with a func in it?

Post by John Cartwright »

Take a look at http://ca3.php.net/manual/en/language.o ... zation.php

Specifically,
In order to be able to unserialize() an object, the class of that object needs to be defined. That is, if you have an object $a of class A on page1.php and serialize this, you'll get a string that refers to class A and contains all values of variabled contained in $a. If you want to be able to unserialize this on page2.php, recreating $a of class A, the definition of class A must be present in page2.php. This can be done for example by storing the class definition of class A in an include file and including this file in both page1.php and page2.php.
Post Reply