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

<?php
class SimpleClass
{
    // Property declaration.
    public $var = 'a default value';

    // Constant declaration.
    const VAR_NAME = 'a value';

    // Class constructor method.
    public function __construct()
    {
        echo self::VAR_NAME;
    }

    // Method declaration.
    public function displayVar() {
        echo $this->var;
    }
}
?>

Instantiate a class

  • PHP library classes are always at the root so simply use one slash.
// Standard class instantiation.
$my_class_instance = new MyClass();
$my_class_instance = new child\MyChildClass();
$my_class_instance = new \MyRootLevelClass();

// Instantiate a new empty class
$my_empty_class_instance = new stdClass();
$my_empty_class_instance = new (object)[]; // Optionally as of PHP 5.4 

Instantiate a class dynamically

// Instantiate a class dynamically
$class_name = '\\Foo\\Bar\\MyClass';
$my_class_instance = new $class_name();

Convert an Object to an Array

$array = json_decode(json_encode($object), true);

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;
}

Autoloading

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.