note 107535 added to language.oop5.magic

From: Date: Wed, 15 Feb 2012 21:48:03 +0000
Subject: note 107535 added to language.oop5.magic
Groups: php.notes 
Request: Send a blank email to php-notes+get-186157@lists.php.net to get a copy of this message
You don't need to serialize the class default values, only those which have changed. It might be important for large objects. Note the example below, for simplicity, always serializes arrays and objects. <?php class MyBaseClass { public $name='object'; // these are default class values public $test=1; public $test2; // equals to NULL in fact public function __construct(){ $this->test2='some text'; // this is not a default value, although called in the constructor } public function __sleep(){ // default class values: $defaults=get_class_vars(get_class($this)); // not __CLASS__ or self::, if you'd like to use in descendant classes // values of $this object: $present=get_object_vars($this); $result=array(); // output array foreach($present as $key=>$value){ if(!is_resource($defaults[$key]) && ( // don't store resources is_object($defaults[$key]) || // always store objects is_array($defaults[$key]) || // and arrays $defaults[$key]!==$value) // and of course all that is not the default value ) // tip: try is_scalar as well $result[]=$key; } return $result; } } $obj1=new MyBaseClass(); echo ($s1=serialize($obj1))."<br>"; // only test2 is stored, as it was changed in the constructor $obj2=new MyBaseClass(); $obj2->name='object 2'; // change default value here echo ($s2=serialize($obj2))."<br>"; // stored name and test2 $obj3=new MyBaseClass(); $obj3->test2=NULL; // switch back to default value echo ($s3=serialize($obj3))."<br>"; // nothing is stored but the class name // let us check if we can retrieve the objects unset($obj1, $obj2, $obj3); $obj1=unserialize($s1); $obj2=unserialize($s2); $obj3=unserialize($s3); var_dump($obj1); var_dump($obj2); var_dump($obj3); ?> ---- Server IP: 82.177.164.100 Probable Submitter: 89.75.186.180 ---- Manual Page -- http://www.php.net/manual/en/language.oop5.magic.php Edit -- https://master.php.net/note/edit/107535 Del: integrated -- https://master.php.net/note/delete/107535/integrated Del: useless -- https://master.php.net/note/delete/107535/useless Del: bad code -- https://master.php.net/note/delete/107535/bad+code Del: spam -- https://master.php.net/note/delete/107535/spam Del: non-english -- https://master.php.net/note/delete/107535/non-english Del: in docs -- https://master.php.net/note/delete/107535/in+docs Del: other reasons-- https://master.php.net/note/delete/107535 Reject -- https://master.php.net/note/reject/107535 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#186157) next »