PHP Objects, Patterns and Practice (3rd edition)

(Barry) #1

CHAPTER 3 ■ OBJECT BASICS


The ShopProduct class in the example is already a legal class, although it is not terribly useful yet. I
have done something quite significant, however. I have defined a type; that is, I have created a category
of data that I can use in my scripts. The power of this should become clearer as you work through the
chapter.


A First Object (or Two)


If a class is a template for generating objects, it follows that an object is data that has been structured
according to the template defined in a class. An object is said to be an instance of its class. It is of the
type defined by the class.
I use the ShopProduct class as a mold for generating ShopProduct objects. To do this, I need the new
operator. The new operator is used in conjunction with the name of a class, like this:


$product1 = new ShopProduct();
$product2 = new ShopProduct();


The new operator is invoked with a class name as its only operand and generates an instance of that
class; in our example, it generates a ShopProduct object.
I have used the ShopProduct class as a template to generate two ShopProduct objects. Although they
are functionally identical (that is, empty), $product1 and $product2 are different objects of the same type
generated from a single class.
If you are still confused, try this analogy. Think of a class as a cast in a machine that makes plastic
ducks. Our objects are the ducks that this machine generates. The type of thing generated is determined
by the mold from which it is pressed. The ducks look identical in every way, but they are distinct entities.
In other words, they are different instances of the same type. The ducks may even have their own serial
numbers to prove their identities. Every object that is created in a PHP script is also given its own unique
identifier (unique for the life of the object), that is, PHP reuses identifiers, even within a process. I can
demonstrate this by printing out the $product1 and $product2 objects:


var_dump($product1);
var_dump($product2);


Executing these functions produces the following output:

object(ShopProduct)#1 (0) {
}
object(ShopProduct)#2 (0) {
}


■Note In PHP 4 and PHP 5 (up to version 5.1), you can print an object directly. This casts the object to a string


containing the object’s ID. From PHP 5.2 onwards the language no longer supported this magic, and any attempt


to treat an object as a string now causes an error unless a method called __toString() is defined in the object’s


class. I look at methods later in this chapter, and I cover __toString() in Chapter 4, “Advanced Features.”


By passing our objects to var_dump(), I extract useful information including, after the hash sign,
each object’s internal identifier.

Free download pdf