30.5. Objects

Versions of PHP prior to version 5.0 had lackluster object support. PHP version 5.0 added more object-oriented support, placing PHP more in line with other modern programming languages. This section gives an overview of PHP's object features.

30.5.1. Class Definitions

Class definitions in PHP begin with the class keyword and enclose the class definition within curly braces (as with most other structures in PHP). A typical class definition would resemble the following:

class <class_name> {
  // Class definition
}

The class name can be any nonreserved word in PHP. Class naming rules are similar to PHP variable naming rules.

30.5.2. Constructors and Destructors

PHP version 5.0 uses a new type of constructor that previous versions don't have. The new format recognizes a function named __construct() in the class definition as the object's constructor. For example, consider the following example object:

class myClass {
  function __construct() {
    // Construction of object
  }
}

For backward-compatibility, PHP version 5.0 will check for the prior versions' constructor format—a function within the class definition named the same as the class. If such a function is not found, PHP version 5.0 will then look for the __construct() function.

An object's constructor is typically used to initialize the object's properties. See the "Methods and Properties" section later in this chapter for more information on object properties. To create a new object (and hence run the class' constructor), ...

Get Web Standards Programmer's Reference: HTML, CSS, JavaScript®, Perl, Python®, and PHP now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.