我创建了一个接口类SellableItems,它是由tv和tennisBall两个产品实现的。两者都包含静态变量$count,我需要在递增和递减之后执行该变量。但是有一个StoreFactory类负责用静态工厂成员函数初始化对象。
问题:
当我测试它对下面给出的代码,我得到一个语法错误:* *
* *解析错误:语法错误,意外的'++' (T_INC) inD: ' xammp '根' ' ' inheritence ' FactoryPattern.php oop实践练习第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();
?>
您在大多数情况下都缺少$
,正如评论中提到的@faintsignal。
您正在使用self::count++;
,它必须是self::$count++;
也许问题是在self::count?您需要在count之前附加$作为变量,而不是方法。