OO in PHP: Part 1 — Classes and Objects

Published 17th May 2010

Scary title I know. But if your a serious developer of any kind then I hope you have heard of Object Oriented programming. You may even have done it without even realising it. What I aim to do in this series is to have a simple and concise look at how to do OO programming in PHP with the aim that you will discover why you should be using it in all of your projects.


What I am not going to do here is explain what OO is. There is plenty of material on the interwebs that explains OO programming and the PHP website even has an Classes and Objects introduction to OO. What I will say is that you will need to be using PHP v5+ to be able to do the OO things I will be showing you.

A Class

So lets get going. A Class is the code you will write and use and is the structure of the Objects that get created when you instantiate a Class. Basically a class holds functions and variables that do a certain task.

class SimpleClass { // property declaration public $var = 'a default value'; // method declaration public function displayVar() { echo $this->var; } }

As you can see above we have a variable and a function. You can call your class whatever you want but it must have the type “class”. Note that when using a variable from within a class it has the prefix “$this->”. That is because you are referencing an object that is itself (hence “this”).

Note the “public” before the variable and function declarations. This means that these variables and functions can be called from outside of the Class when the Object has been created. Instead of “public” you could use “private”. This is known as Encapsulation.

An Object

Thats great but what does it do? Well when you instantiate a class you have created an Object. An Object is the instantiation of a Class that can be used to do the stuff you have defined in the Class. So for example to use our class above:

$obj = new SimpleClass(); $obj->displayVar(); //The output would be 'a default value'

Note that if you hade made the displayVar() function “private” in the Class you would not be able to call $obj->displayVar() here.


So thats probably enough to get you going. Next time we will be looking at inheritance and how it makes OO programming very powerful.