Skip to content

Instantly share code, notes, and snippets.

@Jakiboy
Last active November 9, 2022 00:32
Show Gist options
  • Save Jakiboy/c1301cb722e52a0b74d702ae9d59a126 to your computer and use it in GitHub Desktop.
Save Jakiboy/c1301cb722e52a0b74d702ae9d59a126 to your computer and use it in GitHub Desktop.
PHP Singleton Design Pattern with __construct()
<?php
/**
* @author : JIHAD SINNAOUR
* @package : VanillePlugin
* @version : 0.9.2
* @copyright : (c) 2018 - 2022 Jihad Sinnaour <mail@jihadsinnaour.com>
* @link : https://jakiboy.github.io/VanillePlugin/
* @license : MIT
*/
/**
* Proof of work: Singleton with constructor
*/
final class Singleton // Restrict inheritance
{
/**
* @access private
* @var bool $initialized, Keep instance status in memory
*/
private static $initialized = false;
/**
* __construct
* @param void
*/
public function __construct()
{
// Construct only if not already initialized
if ( !static::$initialized ) {
// Something here
// ...
// Finish initialization
static::$initialized = true;
}
}
/**
* __destruct
*/
public function __destruct()
{
// Something here
// ...
}
/**
* Restrict object clone.
*/
public function __clone()
{
die(__METHOD__ . ': Clone denied');
}
/**
* Restrict object unserialize.
*/
public function __wakeup()
{
die(__METHOD__ . ': Unserialize denied');
}
/**
* Initialize instance.
*
* @access public
* @param void
* @return void
*/
public static function init() : void
{
// Initialize only if not already initialized
if ( !static::$initialized ) {
new static;
}
}
/**
* Return instance.
*
* @access public
* @param void
* @return mixed
*/
public static function returnInstance() : mixed
{
// Return only if not already initialized
if ( !static::$initialized ) {
return new static;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment