Page 207 - Beginning PHP 5.3
P. 207
Chapter 8: Objects
Now that you ’ ve defined a class, you can create objects based on the class. To create an object, you use
the new keyword, followed by the name of the class that you want to base the object on. You can then
assign this object to a variable, much like any other value.
Here ’ s an example that shows how to create objects:
class Car {
// Nothing to see here; move along
}
$beetle = new Car();
$mustang = new Car();
print_r( $beetle ); // Displays “Car Object ( )”
print_r( $mustang ); // Displays “Car Object ( )”
This code first defines the empty Car class as before, then creates two new instances of the Car class —
that is, two Car objects. It assigns one object to a variable called $beetle , and another to a variable
called $mustang . Note that, although both objects are based on the same class, they are independent of
each other, and each is stored in its own variable.
Once the objects have been created, their contents are displayed using print_r() . You ’ ll remember from
Chapter 6 that print_r() can be used to output the contents of arrays. It can also be used to output
objects, which is very handy for debugging object - oriented code. In this case, the Car class is empty, so
print_r() merely displays the fact that the objects are based on the Car class.
In Chapter 7 , you learned how PHP passes variables to and from functions by value, and assigns them
to other variables by value, unless you explicitly tell it to pass them or assign them by reference. The
exception to this rule is objects, which are always passed by reference.
Creating and Using Properties
Now that you know how to create a class, you can start adding properties to it. Class properties are very
similar to variables; for example, an object ’ s property can store a single value, an array of values, or even
another object.
Understanding Property Visibility
Before diving into creating properties in PHP, it ’ s worth taking a look at an important concept of classes
known as visibility . Each property of a class in PHP can have one of three visibility levels, known as
public, private, and protected:
❑ Public properties can be accessed by any code, whether that code is inside or outside the class. If
a property is declared public, its value can be read or changed from anywhere in your script
169
9/21/09 9:03:32 AM
c08.indd 169
c08.indd 169 9/21/09 9:03:32 AM