php - foreach gives me a warning of undefined variable -
this question has answer here:
i'm making class, "item", intent used this:
require_once("item.php"); $myitem = new item(); $myitem->setname("test"); $myitem->adddeal(5,25); $myitem->show();
the show() function should add object on global array called $items
the class in item.php looks this:
$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 image has been set //if(empty($this->image)) // die("error: no image set item: ".$this->name); //make sure atleast 1 deal has been set if(count($this->deals) <= 0) die("error: no deals set item: ".$this->name); //make sure item doesn't exist foreach($items $key => $value) { if($value->name == $this->name) die("error: duplicate item: ".$this->name); } } }
as can see, when show() function gets called, first runs errorcheck() method , proceeds add own object $items array.
or, @ least, that's should happen. because when run in webbrowser warning:
notice: undefined variable: items in c:\xampp\htdocs\shop\config-api.php on line 49 warning: invalid argument supplied foreach() in c:\xampp\htdocs\shop\config-api.php on line 49
why cant find $items variable? , how can fix it? (btw, line 49 @ foreach loop in errorcheck() );
that because variable $items
doesn't belong local scope in function, should indicate use global.
adding function errorcheck fix issue:
global $items;
Comments
Post a Comment