PhpRiot
News Archive
PhpRiot Newsletter
Your Email Address:

More information

Introduction to PHP OOP

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

This is the first in 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.

Since the introduction of PHP 5 in 2004, PHP has had an object model worthy of that description and became a truly modern language for use on the web. Earlier PHP scripts would have been of the kind where, to quote from Alice's Adventures, you would "Begin at the beginning, and go on till you come to the end: then stop." Nowadays that very procedural approach is less common in PHP, so this article takes a look at some of the basic object oriented features available in the language and shows some examples of using them with code examples.

Using OOP (Object Orientated Programming) enables us to architect our systems much more clearly, and to make them more manageable and more maintainable. This technique also allows us to separate form from function to create clean, navigable codebases with plenty of opportunities to reuse code, apply design patterns and bring in concepts from other brances of computer science.

Objects vs Classes

While the terms "object" and "class" are often used almost interchangeably in the world of software, there is a definite conceptual difference between the two. A class is the blueprint or recipe; it describes what the object should be, have and do. So a class might look like this:

class Elephpant { public $colour; A public function dance() { echo "elephpant dances!\n"; return true; } }

elephpant.php

An object, on the other hand, is an actual instantiation of the class - its an actual thing, with values and behaviours. In the example below, $ele is the object:

include('elephpant.php'); A $ele = new Elephpant();

We can inspect $ele to make sure that it is, in fact, an object of the class Elephpant, using the print_r command. Adding this to our code sample as shown, we see the output below:

include('elephpant.php'); A $ele = new Elephpant(); print_r($ele); Elephpant Object ([colour] =)

This output shows an object, of type Elephpant, and with a single empty property named "colour". For more information about the objects exact properties and their values, you can also use var_dump, which gives a more detailed output showing in detail the datatypes of each property. This is particularly useful

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