PHP Classes

PHP is an object oriented language that uses classical inheritance. This means that unlike JavaScript which has only objects, PHP has both classes and objects. The class provides the properties and methods that will be available when an object of this particular type is created.

A simple class is defined in PHP by specifying the keyword 'class' followed by the name you are giving the class followed by the class content wrapped inside of braces. Within the class you can define properties (variables that belong to the class) and methods (functions that belong to the class). The properties and methods can be defined as 'private' if they can only be accessed from other code within the class, 'protected' if they can only be accessed from other code within the class and from code within other classes that are based on this class and 'public' which can be accessed from anywhere in your code. Properties defined using 'var' are considered to be equivalent to if they were defined using 'public'. Methods defined using the function keyword without specifying that they are private or protected are also considered to be public. The properties and methods belonging to the class can be referenced from within the class itself using $this.

Here is what a basic class definition looks like:

class MyClass {
private $var = 'value';
public function getVar() {
return $this->var;

As with all object oriented languages you will generally define the properties as private to the class and provide public getter and setter methods to access those properties.

To create objects of a given class type we use the 'new' keyword in the assignment that creates the object. Once the object has been created we can then reference any public properties and methods of the class from within our code. For example the following creates an object based on the above class definition and then calls the public getVar method of the class.

$myobj = new MyClass();
echo $myobj->getVar();


This article written by Stephen Chapman, Felgall Pty Ltd.

go to top

FaceBook Follow
Twitter Follow