Created
February 3, 2014 20:34
-
-
Save beratdogan/8791849 to your computer and use it in GitHub Desktop.
Defining dispoasble classes with Traits in PHP.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
class DisposableClassException extends \Exception | |
{} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
trait DisposableClassTrait | |
{ | |
protected static $used = false; | |
final public static function getInstance() | |
{ | |
if (static::$used) { | |
throw new DisposableClassException('This class is disposable!'); | |
} | |
static::$used = true; | |
return new static; | |
} | |
final private function __construct() { | |
$this->init(); | |
} | |
protected function init() { | |
echo 'Hey guys! Im from ' . __CLASS__ . '! :)'; | |
} | |
final private function __wakeup() {} | |
final private function __clone() {} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
class OneTimeLifeExample | |
{ | |
use DisposableClassTrait; | |
} | |
// Class initialized! | |
OneTimeLifeExample::getInstance(); | |
// Exception! | |
OneTimeLifeExample::getInstance(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment