note 92311 deleted from language.oop5.magic by danbrown
| From: | danbrown@php.net | Date: | Sat, 18 Jul 2009 23:57:29 +0000 |
| Subject: | note 92311 deleted from language.oop5.magic by danbrown | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-158464@lists.php.net to get a copy of this message | ||
Note Submitter: charlie at dasserver dot com
----
In response to: dhuseby domain getback tld com
As of (at least) php 5.2.6, when overloading the magic __sleep method no special tricks are needed
anymore for private and protected class variables to survive serialization.
Simple illustration:
class dbms {
protected $dbHost = NULL;
protected $dbUser = NULL;
protected $dbPassword = NULL;
protected $dbName = NULL;
protected $dbCharset = NULL;
public function __construct($host, $user, $password, $db, $charset="utf8") {
$this->dbHost = $host;
$this->dbUser = $user;
$this->dbPassword = $password;
$this->dbName = $db;
$this->dbCharset = $charset;
$this->connect();
}
public function __wakeup() {
$this->connect($this->dbHost, $this->dbUser, $this->dbPassword, $this->dbName,
$this->dbCharset);
}
public function __sleep() {
$this->disconnect();
return array('dbHost', 'dbUser', 'dbPassword', 'dbName',
'dbCharset');
}
public function connect() {
// Code to connect to database
}
public function disconnect() {
// Code to disconnect from database
}
public function query($sql) {
// Code to query the database
}
public function secure($value) {
// Code to secure against sql injection
}
}
class account {
private $ary_attribs = array('name' => NULL, 'email' => NULL);
private $dbms = NULL;
public function __construct($account_name, $dbms) {
if (! $dbms instanceof dbms)
throw new Exception("Passed object is not of type DBMS.");
$this->dbms = $dbms;
$this->ary_attribs['account_name'] = $account_name;
$sqlquery = sprintf("UPDATE accounts SET last_login = %u WHERE name = '%s'",
time(), $this->dbms->secure($account_name));
$this->dbms->query($sqlquery);
}
public function __wakeup() {
$this->dbms->__wakeup();
}
public function __sleep() {
return array('ary_attribs', 'dbms');
}
public function __get($attrib) {
return $this->ary_attribs[$attrib];
}
public function __set($attrib, $value) {
$this->ary_attribs[$attrib] = $value;
return true;
}
}
$dbms = new dbms('localhost', 'alice', '123456', 'test');
$account = new account("bob", $dbms);
$account->email = "bob@internet.com";
$serialized = serialize($account);
$newObj = unserialize($serialized);
print_r($newObj); // Bob's email address should not be NULL
exit();