Table of Contents



Introduction

We see in the previous section that we can initialize the properties of an object after it has been created by using the -> object operator.

However, a more direct way is to initialize some or all of the properties at the same time we create the object. To do this, we must add a special __construct() function to the class definition. This special method is called the constructor.

The __construct() Function

We continue with the same User class defined in the previous section. In this example, we will be using a constructor function to initialize both properties of an object at the same time it is created.

Tip

Study and understand the class definition first before reading the rest of the script.

Example

Using a constructor function to initialize properties of an object.

 1<?php
 2    $object1 = new User('Betty',29); // $object1 created with properties initialized
 3    print_r($object1);
 4
 5    echo "<br>";
 6
 7    $object2 = new User('Julian',32); // $object2 created with properties initialized
 8    print_r($object2);
 9
10    echo "<br>";
11
12
13    echo $object1->get_name(); // calls the get_name() method for $object1
14    echo "<br>";
15    echo $object2->get_age(); // calls the get_age() method for $object2
16
17    class User // Class Definition <<==
18    {
19        public $name, $age; // properties
20
21        function get_name() // method to return $name property
22        {
23            return $this->name;
24        }
25
26        function get_age() // method to return $age property
27        {
28            return $this->age;
29        }
30
31        function __construct($name, $age) // constructor
32        {
33            $this->name = $name;
34            $this->age = $age;
35        }
36    }
37?>
User Object ( [name] => Betty [age] => 29 )
User Object ( [name] => Julian [age] => 32 )
Betty
32
Note

  • $object1 = new User('Betty',29) creates an instance of the User class (called $object1) and initializes its properties to 'Betty' and 29.
  • the keyword __construct is written with two underscores.
  • this-> refers to the current object in which the code is running.

For example, the line echo $object1->get_name() means that we are calling the get_name() method for the object $object1 which prints $this->name or equivalently $object1->name.

This will produce the value of the $name property associated with $object1 which is Betty in this case.