I have to log below array of objects in a file and then read it. my variable is $myObject. var_dump($myObject) gives below array:
array(1) {
[0]=>
object(MyClassA)#179 (2) {
["_flag":protected]=>
bool(false)
["_myClassB":protected]=>
array(1) {
[0]=>
object(MyClassB)#187 (5) {
["_flag":protected]=>
bool(false)
}
}
}
MyClassA and MyClassB are two other classes.
How can I log it and retreive it. After retreiving I want to use the methods of MyClassA like MyClassA->getFlag after retreiving.
I am using below method to log it:
$fp = fopen("myfilepath", 'a');
fputcsv($fp, serialize( $myObject));
fclose($fp);
But it's logging in non-readable format.
Thanks
SOLUTION:
I thought serialization creates content in readable format. But I am worng. I am able to get the data when I unserialized it. :)
$stringToSaveInFile = serialize($array);
to reuse:
$array = unserialize($stringToSaveInFile)
the first function (serialize) convert your array/object in a string that you can save where you want... after that, when you'll read that string again, you'll can convert it into an object by the 'unserialize' function
EDIT:
look at this example (edited to save data in a file):
class A
{
public function ciao() {
echo "CIAO";
}
}
class B
{
public function hello() {
echo "HELLO";
}
}
$a = array(new A, new B);
$ser = serialize($a);
file_put_contents('mydata.txt', $ser);
$uns = file_get_contents('mydata.txt');
$uns[0]->ciao();