-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循環中);
看起來像$項目也許是超出範圍。嘗試使用全局關鍵字。 –
我試過了,但它給了我以下錯誤:解析錯誤:語法錯誤,意想不到的'全球'(T_GLOBAL)在C:\ xampp \ htdocs \ shop \ config-api.php 49行 – stav
沒關係,對不起。它現在的作品,即時通訊有點新的PHP,所以我搞砸了全球的語法。隨時讓它成爲一個安澤:) – stav