0

I am trying to make a singleton pattern but it seems I am making mistake somewhere. Everytime i try to create an instance from the class Cart it makes new one. Tested it with the setId() and getId() functions. It returns different number everytime.

class Cart
{
    private $cartQuantity = 0;

    private static $instance;

    private $id;

    private function __construct(){}

    public function addQuantity($quantity){
        $this->cartQuantity += $quantity;
    }

    public function getQuantity(){
        return $this->cartQuantity;
    }

    public function setId(){
        $this->id = rand(0, 10);
    }

    public function getId(){
        return $this->id;
    }

    public static function startCount(){
        if(self::$instance === null){
            self::$instance = new Cart();
            self::$instance->setId();
        }

        return self::$instance;
    }
}

$inst = Cart::startCount();
echo $inst->getId();

What am I doing wrong? Seems like legit block of code to me :/ Thank you in advance!

Toma Tomov
  • 1,476
  • 19
  • 55
  • 2
    "What am I doing wrong" - I think, testing. https://3v4l.org/V9Y9b The code successfully returns same id. – svgrafov Nov 30 '17 at 15:08
  • 1
    yes, works for me as well – musashii Nov 30 '17 at 15:09
  • Hm. OK! Thank you very much! Guess the problem is somewhere else. Will keep searching for it :) – Toma Tomov Nov 30 '17 at 15:11
  • 2
    Since you are making card. I'm guessing you expect the singleton to keep is data between each requests? Maybe you're looking for [session](http://php.net/manual/en/session.examples.basic.php). -- [The Singleton will only live for the current request](https://stackoverflow.com/questions/11633229/singleton-pattern-in-php-how-can-i-save-state-between-requests). – Clément Baconnier Nov 30 '17 at 15:35

1 Answers1

0

Your singleton is working perfectly. I have tested it 10 times with the following code:

$inst = Cart::startCount();
echo $inst->getId();

$winst = Cart::startCount();
echo $inst->getId();

$ninst = Cart::startCount();
echo $ninst->getId();

$ninst->setId();
echo $ninst->getId();
echo $winst->getId();

$ginst = Cart::startCount();
echo $ginst->getId();

Results:

999444
555222
333999
333444
111111
222222
999999
888666
101010999
000777

If you change the ID, it keeps beeing changed. Otherwise always the same is returned. This is exactly what you should expect (note that rand(0,10)) also can deliver 10.

There is never more than one instance.

Blackbam
  • 17,496
  • 26
  • 97
  • 150