Prev | Current Page 69 | Next

Hasin Hayder

"Object-Oriented Programming with PHP5"

PHP5 provides two
magic methods for this purpose named __sleep and __awake. These methods give
some control over the whole process.
More OOP
[ 60 ]
Let's develop all the static variables of a process using these magic methods, which
we generally won't be able to do without a hack. Normally it's not possible to
serialize the values of any static variables and return the object in same state with
that static variable. However, we can make it happen, let's see the following code.
class SampleObject
{
public $var1;
private $var2;
protected $var3;
public static $var4;
private $staticvars = array();
public function __construct()
{
$this->var1 = "Value One";
$this->var2 = "Value Two";
$this->var3 = "Value Three";
SampleObject::$var4 = "Value Four";
}
public function __sleep()
{
$vars = get_class_vars(get_class($this));
foreach($vars as $key=>$val)
{
if (!empty($val))
$this->staticvars[$key]=$val;
}
return array_keys( get_object_vars( $this ) );
}
public function __wakeup()
{
foreach ($this->staticvars as $key=>$val){
$prop = new ReflectionProperty(get_class($this), $key);
$prop->setValue(get_class($this), $val);
}
$this->staticvars=array();
}
}
?>
Chapter 3
[ 61 ]
What happens if we serialize the object, write it into the file and then later retrieve
the state? You will find the static value still persists the last value assigned to it.


Pages:
57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81