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!