php exp9 23
php exp9 23
Experiment No: 9
Title of Experiment Write a simple PHP program on Introspection and Serialization.
Program code:
<?php
class Derived
{
public function details()
{
echo "I am a Derived(super) class for the Child(sub) class. <BR>";
}
}
class sub extends Derived
{
public function details()
{
echo "I'm " .get_class($this) , " class.<BR>";
echo "I'm " .get_parent_class($this) , "'s child.<BR>";
}
}
//details of parent class
if (class_exists("Derived"))
{
$der = new Derived();
echo "The class name is: " .get_class($der) . "<BR>";
$der->details();
}
//details of child class
if (class_exists("sub"))
{
$s = new sub();
$s->details();
if (is_subclass_of($s, "Derived"))
{
echo "Yes, " .get_class($s) . " is a subclass of Derived.<BR>";
}
else
{
echo "No, " .get_class($s) . " is not a subclass of Derived.<BR>";
}
}
Output :
The class name is: Derived
I am a Derived (super) class for the Child(sub) class.
I'm sub class.
I'm Derived's child.
Yes, sub is a subclass of Derived
__sleep(): This method is called before an object is serialized, and allows you to specify
which properties should be included in the serialized representation of the object. If this
method is not defined, all properties will be serialized by default.
__wakeup(): This method is called after an object has been unserialized, and allows you to
perform any necessary post-processing on the object.
__serialize(): This method is called before an object is serialized, and allows you to
customize the serialization process. You can use this method to define custom serialization
logic, or to modify the data that will be serialized.
__unserialize(): This method is called after an object has been unserialized, and allows you to
customize the unserialization process. You can use this method to perform any necessary
post-processing on the data that has been unserialized.
__toString(): This method is called when an object is used in a string context, such as when it
is concatenated with another string. It allows you to define how the object should be
represented as a string.
By implementing these magic methods in your PHP classes, you can customize the behavior
of object serialization and make your code more flexible and robust.
Exercise
1. Declare a class as “Test” with three user defined functions. List name of the class and
functions declared in the class “Test”.
class Test {
public function func1() {
// Function logic here
}