note 107535 deleted from language.oop5.magic by cmb
| From: | cmb@php.net | Date: | Sun, 10 Nov 2019 12:34:55 +0000 |
| Subject: | note 107535 deleted from language.oop5.magic by cmb | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-212978@lists.php.net to get a copy of this message | ||
Note Submitter: Voitcus at wp dot pl
----
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);
?>