Skip to content

Instantly share code, notes, and snippets.

@beratdogan
Created February 3, 2014 20:34
Show Gist options
  • Save beratdogan/8791849 to your computer and use it in GitHub Desktop.
Save beratdogan/8791849 to your computer and use it in GitHub Desktop.
Defining dispoasble classes with Traits in PHP.
<?php
class DisposableClassException extends \Exception
{}
<?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() {}
}
<?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