Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Prodentim Probiotics Specially Designed For The Health Of Your Teeth And Gums

Instant Grammar Checker - Correct all grammar errors and enhance your writing

Teach Your Child To Read

Powerful WordPress hosting for WordPress professionals

Disclosure: My content contains affiliate links.

31,128 questions

40,777 answers

573 users

How to make a class singleton pattern in PHP

4 Answers

0 votes
class Singleton {
    private static $value = null;

    public static function instance(){
        if(!isset(self::$value)){
            self::$value = new self();
        }
        
        return self::$value;
    }
    
    private function __construct() {
        echo "Singleton";
    }
}

$singleton = Singleton::instance();

 
/*
run: 
 
Singleton
  
*/

 





answered Sep 10, 2017 by avibootz
0 votes
final class Factory
{
    public static function Instance()
    {
        static $instance  = null;
        if ($instance === null) {
            $instance = new Factory();
        }
        return $instance;
    }

    private function __construct()
    {
        echo "Factory";
    }
}

$fact1 = Factory::instance();
$fact2 = Factory::instance();

$fact3 = new Factory();

 
/*
run: 
 
Factory
Fatal error: Call to private Factory::__construct() from invalid context in 
C:\xampp\htdocs\allonpage.com\test.php on line 23
  
*/  

 





answered Sep 10, 2017 by avibootz
0 votes
final class Factory
{
    public static function Instance()
    {
        static $instance  = null;
        if ($instance === null) {
            $instance = new Factory();
        }
        return $instance;
    }

    private function __construct()
    {
        echo "Factory";
    }
}

$fact1 = Factory::instance();
$fact2 = Factory::instance();


 
/*
run: 
 
Factory
  
*/

 





answered Sep 10, 2017 by avibootz
0 votes
class Singleton
{
    protected static $instance = null;

    protected function __construct()
    {
        echo "class Singleton";
    }

    public static function getInstance()
    {
        if (!isset(static::$instance)) {
            static::$instance = new static;
        }
        return static::$instance;
    }
}

class Test extends Singleton {};

$obj = Test::getInstance();


 
/*
run: 

class Singleton
  
*/

 





answered Sep 10, 2017 by avibootz
...