Objects and Classes

In Object-Oriented Programming a container called a class holds a collection of functions (called methods when they are in a class). A class does nothing until an instance of it is created (instantiated). Once an instance of a class has been created the methods can be used. A program can use any number of classes.

Defining a Class

class SimpleClass
    // property declaration
    public $var = 'a default value';

    // method declaration
    public function displayVar() {
        echo $this->var;

Instantiating (Creating) a class instance

// Standard class instantiation.
$myClassInstance = new MyClass();
$myClassInstance = new child\MyChildClass();
$myClassInstance = new \MyRootLevelClass();
// PHP library classes
// Are always at the root so simply use one slash.
// Instantiate a class dynamically
$className = '\\Foo\\Bar\\MyClass';
$classInstance = new $className();
// Instantiate a new empty class
$myEmptyClassInstance = new stdClass();

Calling functions and methods

// Call a function programmatically
$func = 'my_function';
$func('param1'); // calls my_function('param1');
// Call a class method programmatically
$my_method_name = 'foo';
$my_class = new MyClass();
$my_class->$my_method_name(); // calls the MyClass->foo() method. 

Convert an object to an array

function obj_to_array($obj)
    return (array) $obj;


In order to instantiate (create an instance of) a class which is defined in a separate file, that file must be included or required into the file currently being executed.