Skip to content

Instantly share code, notes, and snippets.

@SeanJA
Created November 30, 2010 03:32
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 SeanJA/721098 to your computer and use it in GitHub Desktop.
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:
<?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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment