I have been learning PHP for three weeks now and I am trying to understand Object oriented programming. I am learning about classes the last couple of days and I have a question...
Below is the example code of a class given in php.net:
Code:<?php class Cart { var $items; // Items in our shopping cart // Add $num articles of $artnr to the cart function add_item($artnr, $num) { $this->items[$artnr] += $num; } // Take $num articles of $artnr out of the cart function remove_item($artnr, $num) { if ($this->items[$artnr] > $num) { $this->items[$artnr] -= $num; return true; } elseif ($this->items[$artnr] == $num) { unset($this->items[$artnr]); return true; } else { return false; } } } ?>
And, an object is created from the class and used like this:
Code:<?php $cart = new Cart; $cart->add_item("10", 1); $another_cart = new Cart; $another_cart->add_item("0815", 3); ?>
Now, I see that all these codes do is, a function is created in the class and the function is called later...
But couldn't we accomplish this just by creating a function alone? Why do we need to define a class? What is the advantage of it?



Reply With Quote
Bookmarks