Declaring a Class and Instantiating an Object

Jun 19, 2009 Author: LinuxAdmin

Declaring a Class...

The basic declaration of a class is very simple:

class myClass {
// Class contents go here

As you have probably guessed, this advises the PHP interpreter that you are declaring a class called myClass whose contents will normally be a combination of constants, variables and functions (called methods).

Instantiating an Object...

Once you have declared a class, you need to instantiate it in order to take advantage of the functionality it offers. This is done by using the new construct:

$myClassInstance = new myClass();

In PHP 5, objects are treated differently from other types of variables. An object is always passed by reference (in reality, it is passed by handle, but for all practical purposes there is no difference), rather than by value. For example:

$myClassInstance = new myClass();
$copyInstance = $myClassInstance();

In this case, both $myInstance and $copyInstance will point to the same object, even though we didn’t specify that we wanted this to happen by means of any special syntax. This is the standard behaviour of objects in most languages, but wasn’t the case in PHP 4, where objects were handled like any other normal variables and were, therefore, passed by value.

views 3825
  1. Add New Comment