2017-07-28 50 views
-3

的警告,“项目”,这是我有意这样使用:的foreach给了我我正在做一个类未定义的变量

require_once("item.php"); 
$myItem = new Item(); 
$myItem->SetName("test"); 
$myItem->AddDeal(5,25); 
$myItem->Show(); 

的Show()函数应该再加入到对象一个全球性的阵列名为$项目

类本身是item.php看起来像这样:

$Items = array(); 

    class Item 
    { 
    public $Name = "Undefined"; 
    public $Image; 
    public $Deals = array(); 

    public function SetImage($path) 
    { 
     $this->Image = (string)$path; 
    } 

    public function SetName($name) 
    { 
     $this->Name = (string)$name; 
    } 

    public function AddDeal($amount, $price) 
    { 
     $this->Deals[(string)$amount] = (string)$price; 
    } 

    public function Show() 
    { 
     $this->errorCheck(); 

     $Items[$this->Name] = $this; 
    } 

    private function errorCheck() 
    { 
     //Make sure an image has been set 
     //if(empty($this->Image)) 
     // die("Error: No image set for item: ".$this->Name); 

     //Make sure atleast one deal has been set 
     if(count($this->Deals) <= 0) 
      die("Error: No deals set for item: ".$this->Name); 

     //Make sure item doesn't already exist 
     foreach($Items as $key => $value) 
     { 
      if($value->Name == $this->Name) 
       die("Error: Duplicate item: ".$this->Name); 
     } 
     } 
    } 

,你可以看到,当Show()函数被调用时,它首先运行errorCheck( )方法,然后继续将它自己的对象添加到$ Items数组中。

或者,至少,这是应该发生的。因为当我在网页浏览器中运行它时,我得到以下警告:

Notice: Undefined variable: Items in C:\xampp\htdocs\shop\config-api.php on line 49 

Warning: Invalid argument supplied for foreach() in C:\xampp\htdocs\shop\config-api.php on line 49 

为什么不能找到$ Items变量?我该如何解决它? (顺便说一句,第49行在errorCheck()中的foreach循环中);

+0

看起来像$项目也许是超出范围。尝试使用全局关键字。 –

+0

我试过了,但它给了我以下错误:解析错误:语法错误,意想不到的'全球'(T_GLOBAL)在C:\ xampp \ htdocs \ shop \ config-api.php 49行 – stav

+0

没关系,对不起。它现在的作品,即时通讯有点新的PHP,所以我搞砸了全球的语法。随时让它成为一个安泽:) – stav

回答

0

这是因为变量$Items不属于函数中的本地范围,所以应该指示使用全局。

添加以下内容到功能errorCheck将解决这个问题:

global $Items; 
相关问题