Helping ordinary people create extraordinary websites!
HOME TUTORIALS SCRIPTS WEB HOSTING BLOG FORUM
Get Our Newsletter
Email:

Getting Started with Objects with PHP V5

By Matt Zandstra
2005-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



class Dictionary {
public $translations = array();
public $type;
public $dictio;

function __construct( $type, DictionaryIO $dictio ) {
$this->type = $type;
$this->dictio=$dictio;
}

//...

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:



$en = new Dictionary( "En", new DictionaryIO() );

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


 | Bookmark
Related Tutorials:
» Zend Framework Tutorial
» Port Scanning and Service Status Checking in PHP
» Web Database Access from Desktop Applications
» CubeCart 3.0 Installation and Configuration
» PHP Site Search Made Easy
» Installing and Configuring Drupal 6.1

Ask A Question
characters left.