News Archive
PhpRiot Newsletter
Your Email Address:

More information

A Little More OOP in PHP

Note: This article was originally published at Planet PHP on 31 October 2012.
Planet PHP

This post forms part of a series of articles about using PHP to do objected oriented programming, or OOP. They were originally published elsewhere but are no longer available at that location, so I'm reposting them here.

This post follows an earlier entry introducing the basics OOP and what that looks like in PHP. This time around we'll look at some more advanced concepts and some more practical examples of building code, covering use of constructors and how to add access modifiers in to control how calling code can operate on your objects. We'll also show off how to create static methods and properties and, perhaps more importantly, illustrate applications of these features.


Let's start at the very beginning, and look at what happens when we create an object. When a class is instantiated and used to create an object, a particular function is run and this is called the constructor. The way this is done changed between PHP version and so can be a bit confusing. In PHP 4, the constructor was a function with the same name as the class itself - and although PHP 4 is dead and gone (deprecated and no longer supported even for security fixes), that behaviour has been preserved in PHP 5 to preserve backwards compatibility, and you will still see it in code which transitioned between the language versions. Here is an example:

class Penguin { A public function penguin($name) { $this-name = $name; $this-type = "penguin"; } A }


So in PHP 5, this would still work, but really we want to use the magic methods introduced in that version, where the constructor is called __construct() and our class would then look like this:

class Penguin { A public function __construct($name) { $this-name = $name; $this-type = "penguin"; } A }


The PHP 5 version makes a lot more more sense because the method can then be inherited, rather than having to redeclare a same-named function to your new class ... Always use __construct() is the main message here.

The Static Keyword

So far we've looked at fairly classic OO concepts, but to take full advantage of the functionality on offer, there are some more tricks we can learn. One of my favourites (in fact I probably use it too much!) is the static keyword.

The static keyword can be applied to both properties and methods, and we literally mean "static" in this case as to mean "the opposite of dynamic". When we use static properties and methods, we use the class as it stands, without instantiating it. Sounds a bit strange so let's take a look at some examples.

Truncated by Planet PHP, read more at the original (another 16353 bytes)