note 75031 deleted from language.oop5.magic by felipe

[email protected]
Newsgroups php.notes
Message-ID <[email protected]>
Note Submitter: alejandro dot gama at gmail dot com 

----

There is a trick to store static attributes with the objects in the $_SESSION array:

<?
session_start();

class Classes{
  private $name;
  private $statics;

  function __construct($name){
    $this->name=$name;
    $this->statics=array();
  }

  function setStatic($key,$value){
    if(!is_resource($value))
      $this->statics[$key]=$value;
  }
	
  function __wakeup(){
    foreach($this->statics as $k=>$v)
      eval($this->name."::\$".$k."=\$this->statics['".$k."'];");
    unset($this);
  }
}

class Object{
  function __sleep(){
    $name=get_class($this);

    if(empty($_SESSION["_classes"]))
      $_SESSION["_classes"]=array();
		
    if(empty($_SESSION["_classes"][$name])){
      $_SESSION["_classes"][$name]=new Classes($name);
	
      $from_object=get_object_vars($this);
      $from_class=get_class_vars($name);

      if(count($from_object)>0)
        foreach($from_object as $k=>$value)
          if($clave=array_search($k,$from_class))
            unset($from_class[$clave]);

      if(count($from_class)>0)
        foreach($from_class as $k=>$v)
          $_SESSION["_classes"][$name]->setStatic($k,$v);
    }
				
  return $from_object;
  }
	
}
?>

You must inherit all your objects from Object and when you save them in the session the static method from their classes will be store and restore to their original state.

You must have one object from each class (that has static attributes) stored in the session.
lmpx.com only provides a reader for public news (NNTP) servers. It is not affiliated with the servers or forums shown here and is not responsible for the content of articles, which is written by their respective authors.