![]() |
PHP guru, please help. You'll get 30.00 USD$
Im writing a singleton pattern for a shopping basket.
But it keeps creating a new instance of the class when im calling Basket::getInstance(); What do i do wrong, i searched everywhere on google. 30$ to the guy that figure this out. <?php class Basket { private static $instance = null; private $liste; private function __construct() { $this->liste = array(); } public static function &getInstance() { if(self::$instancehahahahanull) { echo "opretter instance".rand(1,10000); self::$instance = new Basket(); } return self::$instance; } public function pushProduct($object) { array_push($this->liste,$object); } public function popProduct($object) { $newListe = array(); for($i=0; $i<count($this->liste);$i++) { if($this->liste[$i]!=$object) { array_push($newListe,$this->liste[$i]); } } $this->liste = $newListe; } public function getList() { return $this->liste; } } ?> This is my main method <?php include_once("class/Basket.php"); $basket = Basket::getInstance(); $basket->pushProduct($object); ?> |
So you are just trying to create a variable that is storing the products and quantity that the user will be purchasing ?
How about using a server side session ? Let me know if I'm following you here. |
Quote:
Its just that its better to know some wellknown patterns. |
Perhaps you should change self::$instancehahahahanull to self::$instance? :winkwink:
|
Ok, well let's try a using a session.
This can be your addcart.php or whatever. http://www.name.com/add.php?id=6 Where 6 is the product we are adding to the basket. Code:
session_start();// start the session If you want to allow the item to be added to the cart more than 1 time. Find and Replace: Code:
echo '<p>This item has already been added to your shopping cart!</p>'; Code:
$_SESSION['cart'][$pid] +1; |
I know it will work with saving the data in a Session. But is it impossible wo get a singleton working ? I dont get it, cause alot of sites is talking about how great it is, that you can make a singleton on php5
|
All times are GMT -7. The time now is 07:31 PM. |
Powered by vBulletin® Version 3.8.8
Copyright ©2000 - 2025, vBulletin Solutions, Inc.
©2000-, AI Media Network Inc123