Restricting acceptable data with type hinting

Started by beingchinmay, 08-19-2016, 06:33:24

Previous topic - Next topic

beingchinmayTopic starter

Let's say that you have developed the simple examples in this chapter ready for deployment in an e-commerce application. Such an application is likely to have a class for the shopping cart and a method called addItem() to add the user's purchases to the cart. To avoid errors, you need to check that the item being added belongs to an acceptable data type. One way of doing so would be to use the instanceof operator like this:

Quotepublic function addItem($item)
{
if ($item instanceof Ch2_Product) {
// It's OK, add it to the cart
} else {
// Reject it
}
}