Using PHP 5.3.8.
I’m attempting to implement two functions, save($adoption) which serializes an Adoption instance, appends a delimiter, then appends it to the end of a text file, and loadAdoptions(), which opens the text file, explode()s the contents on the delimiter, and unserialize()s each object in a for loop through the contents of the array explode() returned then calls Display() on them.
Here’s the shortest form reproducing my problem:
<html><head><title>Request Processed</title></head><body>
<?php
class Dog {
var $name;
}
class Adoption
{
var $dog;
function Display()
{
echo $dog->name;
}
}
function save($adoption)
{
file_put_contents("../adoptions/adoptions.txt", (serialize($adoption)."<!-- E -->"));
}
function loadAdoptions()
{
$filename = '../adoptions/adoptions.txt';
if (file_exists($filename))
{
$datain = file_get_contents($filename);
$out = explode("<!-- E -->", $datain);
echo "<br /><u>Retrieved Data</u><br />";
$count = count($out);
echo 'Count: '.$count;
for ($i = 0; i < $count; $i++)
{
$curAdoption = unserialize($out[i]);
if (curAdoption)
echo $curAdoption->Display();
else
echo 'Error Reading Record.';
echo '<br />';
}
}
}
$newDog = new Dog();
$newDog->name = "Scruffles";
$newAdoption = new Adoption();
$newAdoption->dog = newDog;
save(newAdoption);
loadAdoptions();
?>
</body></html>
On line 38, where Display() is called, Fatal error: Call to a member function Display() on a non-object
Quite a few times, you’ve missed the
$off the front of a variable. Also to access a class’s member variable from a method (getting dog’s name inDisplay()you need to use$this->dog.Working source: