foreach给了我一个未定义变量的警告

时间:2017-07-28 01:56:56

标签: php

我正在上课,"项目",我打算像这样使用:

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

然后,Show()函数应该将对象添加到名为$ Items

的全局数组中

该类本身位于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数组中。

或者,至少,应该发生什么。因为当我在webbrowser中运行它时,我收到此警告:

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循环中);

1 个答案:

答案 0 :(得分:0)

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

将此功能添加到您的函数errorCheck将解决该问题:

global $Items;