News & UpdatesProgrammingWeb programming StoreMy Projects
Links
Affiliates

PHP Tutorial – 10 – Class

A class is a template used to create objects. To define one the class keyword is used followed by a name and a code block. The naming convention for classes is mixed case, meaning that each word should be initially capitalized.

class MyRectangle {}

The class body can contain properties and methods. Properties are variables that hold the state of the object, while methods are functions which define what the object can do. Properties are also known as fields or attributes in other languages. In PHP, they must have an explicit access level specified. The public access level is used below, which gives unrestricted access to the property.

class MyRectangle
{
  public $x, $y;
  function newArea($a, $b) { return $a * $b; }
}

To access members from inside the class the $this pseudo variable is used along with the single arrow operator (->). The $this variable is a reference to the current instance of the class and can only be used within an object context. Without it $x and $y would just be seen as local variables.

class MyRectangle
{
  public $x, $y;
 
  function newArea($a, $b) 
  { 
    return $a * $b; 
  }
 
  function getArea() 
  { 
    return $this->newArea($this->x, $this->y); 
  }
}

Instantiating an object

To use a class’s members from outside the enclosing class, an object of the class must first be created. This is done using the new keyword, which will create a new object or instance.

$r = new MyRectangle(); // object instantiated

The object will contain its own set of properties, which can hold values that are different to those of other instances of the class. As with functions, objects of a class may be created even if the class definition appears further down in the script file.

$r = new MyDummy(); // ok
class MyDummy {};

Accessing object members

In order to access members that belong to an object the single arrow operator (->) is needed. This can be used to call methods or to assign values to properties.

$r->getArea(10, 2); // 20
$r->x = 5; $r->y = 10;

Another way to initialize properties would be to use initial property values.

Initial property values

If a property needs to have an initial value a clean way is to assign the property at the same time as it is declared. This initial value will then be set when the object is created. Assignments of this kind must be a constant expression and cannot, for example, be a variable or a mathematical expression.

class MyRectangle
{
  public $x = 5, $y = 10;
}

Constructor

A class can have a constructor, which is a special method used to initialize (construct) the object. This method provides a way to initialize properties which is not only limited to constant expressions. In PHP, the constructor starts with two underscores followed by the word “construct”.

class MyRectangle
{
  public $x, $y;
 
  function __construct() 
  { 
    $this->x = 5; 
    $this->y = 10; 
    echo "Constructed";
  }
}

When a new instance of this class is created the constructor will be called, which in this example sets the properties to the specified values. Note that any initial property values will be set before the constructor is run.

$r = new MyRectangle(); // "Constructed"

As this constructor takes no arguments the parentheses may optionally be left out.

$r = new MyRectangle; // "Constructed"

Just as any other method the constructor can have a parameter list. This can be used to make the properties’ initial values dependent on the parameters passed when the object is created.

class MyRectangle
{
  public $x, $y;
 
  function __construct($x, $y) 
  { 
    $this->x = $x; 
    $this->y = $y;
  }
}
 
$r = new MyRectangle(5,10);

Destructor

In addition to the constructor, classes can also have a destructor. This special method starts with two underscores followed by the word “destruct”. It will be called as soon as there are no more references to the object, before the object is destroyed by the PHP garbage collector.

class MyRectangle
{
  // …
  function __destruct() { echo "Destructed"; }
}

To test the destructor the unset function can be used to manually remove all references to the object.

unset($r); // "Destructed"

Bear in mind that the object model has been completely rewritten in PHP 5. Therefore, many features of classes, such as destructors, will not work in earlier versions of the language.

Case sensitivity

Whereas variable names are case-sensitive, class names in PHP are case-insensitive – just as function names, keywords and built-in constructs such as echo. This means that a class named “MyClass” can also be referenced as “myclass” or “MYCLASS”.

class MyClass {}
$o1 = new myclass(); // ok
$o2 = new MYCLASS(); // ok

Object comparison

When using the equal to operator (==) on objects these objects are considered equal if the objects are instances of the same class and their properties have the same values and types. In contrast, the identical operator (===) returns true only if the variables refer to the same instance of the same class.

class Flag {
  public $flag = true;
}
$a = new Flag();
$b = new Flag();
 
$c = ($a == $b);  // true (same values)
$d = ($a === $b); // false (different instances)
Recommended additional reading:
Sams - Teach Yourself PHP in 24 Hours