Core Function Serialize
From Sputnik Wiki
Serialize( <variable> )
Contents |
Description
Convert a variable, array, class etc a string you can save to file or transfer over the internet.
Parameters
variable
The variable to serialize.
Return Value
Success: Returns serialized variable.
Failure: Returns null.
Remarks
This can be used as a very fast effective way to dump arrays/classes to a file and read it back later.
It is faster than the JSON stuff however it is not as portable and will only work within Sputnik.
To read this in another language you would need to first read it into Sputnik then dump it as JSON.
Example
Serialize a string
// Make a value $a = "Hello"; // Serialize it my $s = Serialize($a); // Print the serialized say $s; // PRINTS // p:5:"Hello"; // Unserialize is my $b = Unserialize($s); // Print it say $b; // PRINTS // Hello
Serialize a number
// Make a value $a = 777; // Serialize it my $s = Serialize($a); // Print the serialized say $s; // PRINTS // l:777; // Unserialize is my $b = Unserialize($s); // Print it say $b; // PRINTS // 777
Serialize an array
// Make an array // Note - You could include multiple arrays inside arrays and so on $a = array(100, "Cat", "Dog"); // Serialize it my $s = Serialize($a); // Print the serialized say $s; // PRINTS // a:l:3;l:0;l:3;i:0;:{l:0;l:100;l:1;p:3:"Cat";l:2;p:3:"Dog";} // Unserialize is my $b = Unserialize($s); // Print it printr $b; // PRINTS // Array // ( // [0] => 100 // [1] => Cat // [2] => Dog // )
Serialize a class
// Make a Class Class Test { my $cat; my $dog; // This function is called when you create a class Function __Construct($catGoes, $dogGoes) { $cat = $catGoes; $dog = $dogGoes; say "Class 'Test' made"; } // This function is called when you serialize a class Function __Sleep() { say "Class 'Test' sleeps"; } // This function is called when you unserialize a class Function __WakeUp() { say "Class 'Test' woken up"; } }; // Create class instance $a = new Test('meow', 'woof'); // Serialize it my $s = Serialize($a); // Print the serialized say $s; // PRINTS // oc:p:4:"test";{a:l:2;l:0;l:0;i:2;:{p:3:"cat";p:4:"meow";p:3:"dog";p:4:"woof";}} // Unserialize is my $b = Unserialize($s); // Print it printr $b; // PRINTS // test Class // ( // [cat] => meow // [dog] => woof // ) // Lets double check it worked by calling the classes variables say "Cat goes? : " . $b->$cat; say "Dog goes? : " . $b->$dog; // PRINTS // Cat goes? : meow // Dog goes? : woof