0
votes

I have a custom class in PHP. If I serialize the class and save it to a text file, I can't unserialize it later in another php file. When I try to call the class functions on the object I get

Call to a member function [functioname()] on a non-object...

I do include the class in both php files.

PHP File 1:

$myobject = new myclass();
$temp = serialize($myobject);
file_put_contents('serializetest.txt', $temp);

PHP File 2:

$s = file_get_contents('serializetest.txt');
$newobject = unserialize($s);

Is there some reason why a serialized class would unserialize properly?

Update

If I create an object and use it's main function I can unserialize the unrelated saved object. The class searches for criminal cases. Even though the two objects are entirely different, once I create and use the new object I can suddenly unserialize saved past objects. i.e. The below works but if I removed the first 3 lines of code it wouldn't.

$tempcase = new Expungement();
$tempcase->searchCase('4B02305986','Public',true,false);
echo "Case Number 1: " . $tempcase->caseno;

$s = file_get_contents('serializetest.txt');
echo "Serialized Data: " . $s;
$newcase = unserialize($s);
echo "Case Number 2: " . $newcase->caseno;
1
Does the class definition exist in file 2? File 2 would still need to know what myclass is. - Devon
I include the class file at the top of both pages. include_once 'myclass.php' - MatthewExpungement
You tried dumping $newobject to see what is contains? - Devon
All it comes up with is this " bool(false)". See my comment below though. If I create an unrelated object and use it's main function (which uses other classes) it works. Maybe it's not importing the other classes into memory until they are used? - MatthewExpungement
If unserialize returned false, then you need to check the contents of $s. - Devon

1 Answers

0
votes

Have you checked content of "serializetest.txt" and value of $s? Are file 1 and file 2 in the same directory? Sometimes unserialize doesn't work good if you have "complicated" classes with many crossreferences.