Search code examples
phpstaticfactory-pattern

Unable to increment Static Class Variable PHP


I have created an Interface class SellableItems which is implemented by the two products tv and tennisBall. The both contain a static variable $count, which I need to perform post increment and decrement. However there is a StoreFactory class responsible for initializing objects with a static factory member function.

PROBLEM :

When I Test It Against the code given below I am getting a syntax error: **

Parse error: syntax error, unexpected '++' (T_INC) in D:\xammp\htdocs\practice\oop practice\inheritence\FactoryPattern.php on line 36

**

<?php

 interface SellableItems{
    public function addItem();
    public function removeItem();

 }

 class tennisBall implements SellableItems{
    public static $count=0;

    public function addItem(){
        return self::$count++;
    }
    public function removeItem(){
        if(self::count>0){
        return self::count--;
        }
        else {
            echo "<br/>Sorry, Stock empty";
        }
    }
    public function ShowData(){
        echo "<br/>There are ".self::$count." ".__CLASS__;

    }
 }


 class tv implements SellableItems{
    static $count=0;

    public function addItem(){

        return self::count++;
    }
    public function removeItem(){
        if(self::count>0){
        return self::count--;
        }
        else {
            echo "<br/>Sorry, Stock empty";
        }
    }
    public function ShowData(){

        echo "<br/>There are ".self::$count." ".__CLASS__;

    }
 }


 class StoreFactory{

    public static function factory($item){

        switch($item){
            case "tennisBall":
                $product=new tennisBall();

            break;

            case "tv":
                $product=new tv();
            break;

            default:
            die("<br/>WRONG Choice OF PRODUCT: {$item}");

        }
        if($product instanceof SellableItems){
            return $product;

        }
        else{
            die("</br>Sory cannot create particular Product");
        }

    }


 }

$Instance=StoreFactory::factory("tennisBall");
$Instance->addItem();
$Instance->addItem();

$Instance->ShowData();

?>

Solution

  • You are missing $ in most of the cases as @faintsignal mentioned in comments.

    You are using self::count++; it must be self::$count++;