Introspection and serialization in PHP

Introspection in PHP:
Introspection in PHP offers the useful ability to examine an object's characteristics, such as its name, parent class (if any) properties, classes, interfaces, and methods.
PHP offers a large number of functions that you can use to accomplish the task.
The following are the functions to extract basic information about classes such as their name, the name of their parent class and so on.
In-built functions in PHP Introspection :
FunctionDescription
class_exists()Checks whether a class has been defined.
et_class()Returns the class name of an object.
get parent_class()Returns the class name of a Return object's parent class.
is_subclass_of()Checks whether an object has a given parent class.
get_declared_classes() Returns a list of all declared classes.
get_class_methods() Returns the names of the class methods.
get_class_vars()Returns the default properties of a class
interface_exists()Checks whether the interface is defined.
method_exists()Checks whether an object defines a method.


Example 1:
<?php

if(class_exists('cwipedia'))
{
 $ob=new cwipedia();
 echo "This is cwipedia.in";
}
else
{
 echo "Not exist";
}

?>
Output: Not exist
Example 2:
<?php
class cwipedia
{
 //decl
}
if(class_exists('cwipedia'))
{
 $ob=new cwipedia();
 echo "This is cwipedia.in";
}
else
{
 echo "Not exist";
}

?>
Output: This is cwipedia.in

Serialization in PHP:
Serialization is a technique used by programmers to preserve their working data in a format that can later be restored to its previous form.

Serializing an object means converting it to a byte stream representation that can be stored in a file.

Serialization in PHP is mostly automatic, it requires little extra work from you, beyond calling the serialize() and unserialize() functions.

Serialize():
The serialize() converts a storable representation of a value.
The serialize() function accepts a single parameter which is the data we want to serialize and returns a serialized string
A serialize data means a sequence of bits so that it can be stored in a file, a memory buffer, or transmitted across a network connection link. It is useful for storing or passing PHP values around without losing their type and structure.

Syntax:
serialize(value);

unserialize():
unserialize() can use string to recreate the original variable values i.e. converts actual data from serialized data.

Syntax:
unserialize(string);

Example:
<?php
$a=array('Shivam','Rahul','Vilas');
$s=serialize($a);
print_r($s);
$s1=unserialize($s);
echo "<br>";
print_r($s1);
?>
Output:
a:3:{i:0;s:6:"Shivam";i:1;s:5:"Rahul";i:2;s:5:"Vilas";}
Array ( [0] => Shivam [1] => Rahul [2] => Vilas )


Comments