Microsoft Word - Core PHP Programming Using PHP to Build Dynamic Web Sites

(singke) #1

One issue you might wonder about is whether and how constructors are inherited. While
they are inherited along with all other methods, they cease to have the property of being
called when an object is created from the class. If you require this functionality, you must
write it explicitly by calling the parent class's constructor within the child class's
constructor.


Creating an Object


Once you have defined a class, you use the new statement to create an instance of the
class, an object. If the definition of the class is the blueprint, the instance is the widget
rolling off the assembly line. The new statement expects the name of a class and returns a
new instance of that class. If a constructor with parameters has been declared, you may
also follow the class name with parameters inside parentheses. Look for the line in
Listing 6.1 that uses the new statement.


When you create an instance, memory is set aside for all the properties. Each instance has
its own set of properties. However, the methods are shared by all instances of that class.


As you recall, PHP allows you to create variables without explicitly declaring the type.
Objects are no different. You can create an object simply by using it in the proper
context. That is, using the -> operator on a variable will make it an object. You can create
as many properties as you wish on this new object just by referring to them.
Unfortunately, you will not be able to attach methods to an object this way.


Another way to create an object is to change the type of an array. When an array becomes
an object, all the elements indexed by strings become properties. Elements indexed by
numbers will remain with the variable but will be inaccessible. If the variable later
returns to being an array, the numbered elements will be accessible again. This is similar
to what happens when an object is cast as an array. All properties will be available as
array elements, but methods are not. When an object is created through casting or
inference, it is of type stdClass.


Accessing Properties and Methods


The properties of an instance are variables, just like any other PHP variable. To refer to
them, however, you must use the -> operator. You do not use a dollar sign in front of the
property name. For an example, refer to the line in Listing 6.1 that prints the name
property of the currentUser object.


Use of -> can be chained. If an object's property contains an object itself, you can use
two -> operators to get to a property on the inner object. The parser in PHP 3 was unable
to deal with complex expressions like this. In PHP 4 you are not limited this way. You

Free download pdf