一个php的类的问题

来源:百度知道 编辑:UC知道 时间:2024/07/02 19:04:14
8 <?php
9 class b
10 {
11 var $name;
12 var $item;
13 function __construct($customer)
14 {
15 $this->name=$customer;
16 echo $this->name."'s buying process<br>";
17 }
18 function add_item($things,$num)
19 {
20 $this->item[$things]+=$num;
21 echo "add ".$num." ".$things." .";
22 echo "total have ".$this->item[$things]." ".$things."<br>";
23 }
24
25 }
26
27
28 $buy=new b("someone");
29 $buy->add_item("apple",2);
30
31 ?>

这个是我一个还没写完的程序
但是运行起来是这么提示的:
PHP Notice: Undefined index: apple in D:\web\test\0012.php on line 20

因为使用了‘+=’,所以在使用$this->item[$things]前必须要赋值,在第20行前加上$this->item[$things]="";

<?php
class b
{
var $name;
var $item;
function __construct($customer)
{
$this->name=$customer;
echo $this->name.'s buying process<br>';
}
function add_item($things,$num)
{
$this->item[$things]+=$num;
echo ' add '.$num.' '.$things;
echo ' total have '.$this->item[$things].' '.$things.'<br>';
}

}

$buy=new b("someone");
$buy->add_item("apple",2);
//我那里测试通过 如果你那不行 你检查下环境吧
?>