samedi 24 septembre 2016

can't make sure only one instance is created in singleton pattern

I am trying to create a class which can be instantiate once.

$ins1,$ins4,$ins3 

are created in such a way that if a static variable $instance is already defined it will be returned again and again.

$ins1==$ins4 returns true

instances $ins4,$ins5 are created with new keyword.When i use

$ins4==$ins5

it also returned ture.How can i be sure that only one instance is created

<?php
class Singleton{

     private static $instance;

       public static function getInstance(){

            if(!self::$instance){
                echo " I AM THE FIRST INSTANCE and i am not from bypass<br>";
                self::$instance = new Singleton();
                return self::$instance;
            }else{
                echo "i am from bypass<br>";
                return self::$instance;
            }
       }

}

$ins1 = Singleton::getInstance();
$ins2 = Singleton::getInstance();
echo $ins1==$ins2;
echo '<br>';
$ins3 = Singleton::getInstance();

$ins4 = new Singleton();
$ins5 = new Singleton();

echo $ins4 == $ins5;
?>

Aucun commentaire:

Enregistrer un commentaire