Pro PHP- Patterns, Frameworks, Testing and More

(vip2019) #1
CHAPTER 12 ■ SPL ARRAY OVERLOADING^183

Listing 12-4. Cart Object

require_once('Product.php');

class Cart extends ArrayObject {

protected $_products;

public function __construct() {
$this->_products = array();

/*
Construct the underlying ArrayObject using
$this->_products as the foundation array. This
is important to ensure that the features
of ArrayObject are available to your object.
*/
parent::__construct($this->_products);
}

}

$cart = new Cart();
$product = new Product('00231-A', 'Description', 1.99);

$cart[] = $product;

print_r($cart);

Cart Object
(
[0] => Product Object
(
[_partNumber:protected] => 00231-A
[_description:protected] => Description
[_price:protected] => 1.99
)

)

You now have a Cart object that behaves as an array. But you could have simply used an
array for this. So what does this technique add? It lets you encapsulate other methods within
this class. For example, you could add the ability to get a price total of all items that are currently in
the cart. Listing 12-5 shows a method for this functionality that you can add to your Cart class.

McArthur_819-9C12.fm Page 183 Thursday, February 28, 2008 7:51 AM

Free download pdf