Created
November 30, 2010 03:32
-
-
Save SeanJA/721098 to your computer and use it in GitHub Desktop.
Make the clone/construct methods private and final, so I cannot do this:
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 | |
abstract class Singleton { | |
private function __construct() { | |
// empty | |
} | |
public static function getInstance() { | |
static $instance = null; | |
return $instance ?: $instance = new static; | |
} | |
//attempt to prevent cloning of an object | |
public function __clone() { | |
trigger_error('Clone is not allowed.', E_USER_ERROR); | |
} | |
} | |
//no longer a singleton... even though it extends singleton | |
class oops extends Singleton{ | |
public $test = 'test'; | |
public function __clone(){ | |
return $this; | |
} | |
} | |
//no longer a singleton, see? | |
$oops = oops::getInstance(); | |
$oopsClone = clone $oops; | |
$oopsClone->test = 'not test'; | |
var_dump($oopsClone, $oops); // not the same oops |
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
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment