Welcome to collectivesolver - Programming & Software Q&A. A website you can trust. I check, compile and run every program. Contact me at: aviboots(AT)netvision.net.il

Hostgator - Save 50% Off Your New Optimized WordPress Hosting With Coupon: WDA50

BlueHost Web Hosting

Ecommerce Software - Best Ecommerce Platform Made for You - Free Trial

Dedicated Hosting Superb Internet

Ecommerce Software - Best Ecommerce Platform Made for You - Free Trial

getflywheel wordpress hosting


Distribute your Resume to 500+ Job Boards & Recruiters


6,580 questions

9,399 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 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 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 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 by avibootz
...