0

im trying to make my first class in php from an exmple

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

What i have:

file 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

    <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

I cant fix it, can some one help me?

1
  • 1
    The array key does not exist. Commented Feb 7, 2014 at 13:51

1 Answer 1

6

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";
  }
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks it is working now, kinda weard i thought it was a official tutorial ;)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.