Constructors

It is possible to automatically execute a function when the class is called to create a new object. This is referred to as a constructor. In order to use it, your PHP 5 class definition must contain a special function, __construct().

 Example PHP 5

For example, if you'd like all newly born bears to be brown and weigh 100 units, you could add this to your class definition:

In PHP 4, your constructor must have the same name as the class. Here's the equivalent code for PHP 4:

 Example PHP 4

Constructors automatically set default properties every time an object of the class is instantiated. Therefore, when you create a new Bear, your bear will be brown and weigh 100 units at birth.