How to declare Classes in PHP

Since PHP 5 we can use object oriented features in PHP. This allows us to not only use functions and variables, but also write classes and create instances of them in our code.

Here’s quick rundown on how to do it.

Writing and instantiating a Class

Creating classes is very similar to writing functions. Here’s an example of a class with one method and one variable:

Once declared, we can instantiate our class like this:

Accessing variables and methods

Now we can access any variables in our instance using the -> operator like this:

The same principle is true for calling methods in our instance.

Constructor Methods

A method is nothing other than a function really, but when a function is part of a class, we call it method. I guess that’s done to differentiate it from a “classic” function that’s declared outside of a class.

There’s a special method we can declare inside our classes called a constructor method. It works just like a regular method, with the only difference that the constructor is called automatically when the class is instantiated. This is useful if we want something to happen as soon as our class is used the first time.

Constructors have a special name (__construct); here’s an example:

Extending a Class

Classes can inherit functionality from other classes. When we do that we create an exact duplicate of an existing class. This is useful if we want to change the behaviour of a class, for example by overwriting existing methods or values.

Here’s how we can extend a class:

Overwriting methods and variables is as easy as simply re-declaring them using their original names. Extended classes can be extended again, but a class can only ever inherit from another single class.

Notice the use of the parent:: keyword in our constructor method. When our extended class is instantiated, our constructor method is called. If our parent class also has a constructor method (which is optional), we must call this before doing anything else to make sure that any functionality that is setup is being kicked off.

In essence, anything prefixed with the parent:: keyword will call the related function “one level up”.

Now we can create an instance of our extended class as described above:

Jay is the CEO and founder of WP Hosting, a boutique style managed WordPress hosting and support service. He has been working with Plesk since version 9 and is a qualified Parallels Automation Professional. In his spare time he likes to develop iOS apps and WordPress plugins, or draw on tablet devices. He blogs about his coding journey at http://wpguru.co.uk and http://pinkstone.co.uk.

One thought on “How to declare Classes in PHP

Add your voice!