Pro PHP- Patterns, Frameworks, Testing and More

(vip2019) #1

(^184) CHAPTER 12 ■ SPL ARRAY OVERLOADING
Listing 12-5. Adding a getCartTotal Method
public function getCartTotal() {
for(
$i=$sum=0, $cnt = count($this);
$i<$cnt;
$sum += $this[$i++]->getPrice()
);
return $sum;
}
This method uses a single for loop to iterate over all the products in the cart by using $this
as an array and calling getPrice() on each element. When this method is included in the Cart
class, you can easily get the cart total, as shown in Listing 12-6.
Listing 12-6. Summing the Cart
$cart = new Cart();
$cart[] = new Product('00231-A', 'A', 1.99);
$cart[] = new Product('00231-B', 'B', 1.99);
echo $cart->getCartTotal();


3.98

For operation within a session environment, this $cart object can be added to the $_SESSION
array, and it will be properly serialized/deserialized for you automatically.
Using this approach allows you to create an easily managed cart that encapsulates all cart
functionality into a single class.

Using Objects As Keys


Normally, it is difficult to use an object as the key of an array in PHP. For example, suppose you
try to run the following code:

class MyObject {}

$a = new MyObject();
$b = array($a=>'Test');

You will get the following warning, and the entry will be ignored.

Warning: Illegal offset type in yourfile.php on line.

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

Free download pdf