Skip to content

Instantly share code, notes, and snippets.

@myanmarlinks
Created August 9, 2017 15:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save myanmarlinks/d977cbe75b060b81770e153aecaa0bb8 to your computer and use it in GitHub Desktop.
Save myanmarlinks/d977cbe75b060b81770e153aecaa0bb8 to your computer and use it in GitHub Desktop.
Magic Method __sleep() and __wakeup()
<?php
class Connection {
protected $link;
private $dsn, $username, $password;
public function __construct($dsn, $username, $password) {
$this->dsn = $dsn;
$this->username = $username;
$this->pasword = $password;
$this->connect();
}
private function connect() {
$this->link = new PDO($this->dsn, $this->username, $this->password);
}
private function disconnect() {
unset($this->link);
}
public function __sleep() {
echo "It's time to sleep! <br>";
$this->disconnect();
return ['dsn', 'username', 'password'];
}
public function __wakeup() {
echo "It's time to wake up! <br>";
$this->connect();
}
}
$connection = new Connection("mysql:host=localhost;dbname=wpa26data", "root", "");
$con = serialize($connection);
var_dump($con);
unserialize($con);
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment