Getting Started with Objects with PHP V5
By Matt Zandstra2005-07-01
The constructor
The PHP engine recognizes a number of "magic" methods. If they are defined, it invokes these methods automatically when the correct circumstances arise. The most commonly implemented of these methods is the constructor method. The PHP engine calls a constructor when the object is instantiated. It is the place to put any essential setup code for your object. In PHP V4, you create a constructor by declaring a method with the same name as that of the class. In V5, you should declare a method called
__construct(). Listing 6 shows a constructor that requires a DictionaryIO object.Listing 6. A construtor that requires a DictionaryIO object |
To instantiate a Dictionary object, you need to pass a type string and a DictionaryIO object to its constructor. The constructor uses these parameters to set its own properties. Here is how you might now instantiate a Dictionary object:
|
The Dictionary class is now much safer than before. You know that any Dictionary object will have been initialized with the required arguments.
Of course, there's no way yet to stop someone coming along later and changing the $type property or setting $dictio to null. Luckily, PHP V5 can help you there, too.
Tutorial Pages:
» Why you need to know objects and classes, and how to use them
» What are classes and objects?
» A first class
» Properties
» Methods
» The constructor
» Keywords: Can we have a little privacy in here?
» Working in class context
» Inheritance
» Summary
» Resources
First published by IBM DeveloperWorks
