简体   繁体   English

添加到数组时的未定义索引

[英]Undefined index on add to array

im trying to make my first class in php from an exmple 我试图从一个例子中使我的第一堂课在PHP

http://www.php.net/manual/en/keyword.class.php http://www.php.net/manual/zh/keyword.class.php

What i have: 我有的:

file cart.php 文件cart.php

<?php
class Cart
{
  private $items; //items in our cart

  public function Cart()
  {
      $this->add_item("03", 0);
  }

  public function add_item ($artnr, $num)
  {
    $this->items[$artnr] += $num;
    echo "product added";
  }
}
?>

file index.php 文件index.php

    <html>
<head>
<?php
include_once('cart.php');
?>
<title>Test</title>
</head>
<body>
<?php

     $test1 = new Cart();

?>
</body>
</html>

but it crashes on the line 但它崩溃了

    this->add_item("03",0);

witht he error Undefined index: 03 in 错误但未定义索引:03 in

I cant fix it, can some one help me? 我无法解决它,有人可以帮我吗?

You need to check if that array key exists before you append to it. 您需要先检查该数组键是否存在, 然后再追加。 If it doesn't exist you need to create it first, then append to it. 如果不存在, 需要先创建它, 然后附加到它。

  public function add_item ($artnr, $num)
  { 
    if (!isset($this->items[$artnr])) {
        $this->items[$artnr] = 0;
    }
    $this->items[$artnr] += $num;
    echo "product added";
  }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM