Table of Contents



Introduction

Before you can use an object, you must define a class with the class keyword. Class definitions contain the class name (which is case-sensitive), its properties, and its methods.

Defining a Class

Syntax

Defining a PHP Class.

 1<?php
 2    class className // class name
 3    {
 4        public $property_1, $property_2; // properties
 5
 6        function method_1() //method
 7        {
 8            statement(s);
 9        }
10    }
11?>

In the above class definition, we defined a class with the class keyword. The name of the class is className (which is case-sensitive). We also include two properties ($property_1 and $property_2) using the public keyword. More on the public keyword later. Let’s take a look at an example first.

Example

Defining a class and creating an instance.

 1<?php
 2    $object = new User;
 3    print_r($object);
 4
 5    class User
 6    {
 7        public $name, $age;
 8
 9        function say_something()
10        {
11        echo "Method statements go here";
12        }
13    }
14?>
User Object ( [name] => [age] => )

In the above example, we define the class User with two properties $name and $age. We also create a new instance (called $object) of the class. I have also used print_r to display $object. Note that echo will not be able to display objects.

Tip

Use print_r to display the contents of an object.

In the above output, we see that both properties $name and $age are not initialized yet.

Initializing Properties and Calling Methods

In the following example, we have the same User class defined above. After creating an instance of the class called $object, we also initialize its two properties using the syntax $object->property = value, taking note that the $ is left out from the property name. The -> character pair is called the object operator and we use it to access an object’s properties and methods.

We also call the object’s method using a similar syntax $object->method().

Example

Initializing properties and calling a method.

 1<?php
 2    $object = new User;
 3    print_r($object);
 4
 5    echo "<br>";
 6
 7    $object->name = "Julian"; // initialize object's name property
 8    $object->age = "32"; // initialize object's age property
 9    print_r($object);
10
11    echo "<br>";
12
13    $object->say_something(); // calling object's method
14
15
16    class User
17    {
18        public $name, $age;
19
20        function say_something()
21        {
22        echo "Method statements go here.";
23        }
24    }
25?>
User Object ( [name] => [age] => )
User Object ( [name] => Julian [age] => 32 )
Method statements go here.
Tip

We can place the class definitions anywhere in the script, either before or after the statements that use them.

In the above example, we placed the class definition at the end of the script. Note that after initialization, the values of both properties are displayed: User Object ( [name] => Julian [age] => 32 ).