Skip to content

OOP in PHP - Part 1

Peter's WebDev Workshop

Apologies. It's been literally months since I did my last tutorial here. Most of my tutorial effort has been focused on FOSSwire. Anyway, I'm back now and thanks to a request from Nick I'm starting a new multi-part tutorial today.

Now this has been covered in many places before and the subject is object-oriented programming (OOP) in PHP. For the purposes of this tutorial, I'm using PHP 5.1.6 on Linux, but all of this should work on PHP 5.x on any platform and most of it will work in PHP 4.x.

Before we jump in and start coding, what exactly is object-oriented programming? Well, Wikipedia defines it as:

Object-oriented programming (OOP) is a programming paradigm that uses abstraction to create models based on the real world. It utilizes several techniques from previously established paradigms, including modularity, polymorphism, and encapsulation. Even though it originated in the 1960s, OOP was not commonly used in mainstream software application development until the 1990s. Today, many popular programming languages (such as Java, JavaScript, C#, C++, Python) support OOP.

Ouch. Let's break it down.

Object-oriented programming, as the name suggest, revolves around objects. Now I could go into the whole theory behind it, but I'm going to try and jump in and get some key terms in your head rather than going through everything. This isn't a long-winded introduction to the fundamentals behind OOP - this is a crash course to get you up and running with everything you need, but not a lot more.

Classes

A class is one of the very useful things we will be using in OOP. In the simplest sense, you can use classes just to group similar functions and subroutines together. For now, that's all we'll do.

OK, I have a few functions that deal with my database that my app often uses.

PHP:
  1. <?php
  2.  
  3. function checkEmailAddress($email) {
  4.  
  5.  
  6.     // checks to see if an email address is valid or not
  7.  
  8.     if (!eregi("^[[:alnum:]][a-z0-9_.-]*@[a-z0-9.-]+\.[a-z]{2,6}$", $email))
  9.         return false; // invalid
  10.     else
  11.         return true; // valid
  12.  
  13. }
  14.  
  15. function connectToDB() {
  16.  
  17.     $conn = mysql_connect("localhost", "blah", "blah", "monkeys");
  18.     mysql_select_db("ilikemonkeys");
  19.  
  20. }
  21.  
  22. function makeStringSafe($string) {
  23.  
  24.         if (!get_magic_quotes_runtime()) // if magic quotes is off
  25.             $newstr = mysql_real_escape_string($string); // escape string
  26.  
  27.         else    // otherwise magic quotes has done the job
  28.             $newstr = $string;
  29.  
  30.  
  31.         return $newstr;
  32.  
  33. }
  34.  
  35. function helloWorld() {
  36.  
  37.     connectToDB();
  38.  
  39.     $q = mysql_query("select * from monkeytable order by monkeyid desc limit 1;") or die ("failed");
  40.  
  41.     $r = mysql_fetch_assoc($q);
  42.  
  43.     echo $r['monkeyid'];
  44.  
  45. }
  46.  
  47. ?>

You'll notice that these are all to do with the database. Now at the moment, it's fairly easy to reuse these functions. We can store them in a separate file and just include() or require() it and call our functions.

But - what if we have loads of functions? What if we have functions' names clashing? Now things start to get messy and you can quickly lose track of your functions, variables and pull your hair out. Oh - and if you want to reuse your code in another project, you have to go hunting through hundreds of lines of useless stuff to find what you're looking for.

So, we'll put all this database stuff in a class. There are also other benefits of using classes, which we'll look into a bit later.

Warning - this is not a very good tutorial at explaining classes and the OOP ideas, as I've said. I'm getting you up and running with OOP in PHP, not explaining OOP. You should read up on OOP first ideally.

To declare a class, use the class keyword and then give your class a name. I'll use dbIO as mine - for database input/output.

PHP:
  1. <?php
  2. class dbIO
  3. {

Everything from this starting curly bracket to the ending one is inside your class. At the end of your class, you need to use a curly bracket followed immediately by a semicolon.

PHP:
  1. };

In our class, we can have the following things:

  • Variables - we set class-wide variables using the var keyword. These are accessible inside all the functions in our class. By default, a class-wide variable is public (meaning code outside the class can access and change it), but in PHP 5, you can declare them private (or protected).
  • Functions - these are what do all the work. Each class can have as many functions as you want, that can also be used only internally or can be called from outside the class.

Converting to classes

OK, so let's convert our set of functions into a DB input/output class. Here's the full code.

PHP:
  1. <?php
  2.  
  3. class dbIO
  4. {
  5.  
  6.     function checkEmailAddress($email) {
  7.    
  8.    
  9.         // checks to see if an email address is valid or not
  10.    
  11.         if (!eregi("^[[:alnum:]][a-z0-9_.-]*@[a-z0-9.-]+\.[a-z]{2,6}$", $email))
  12.             return false; // invalid
  13.         else
  14.             return true; // valid
  15.    
  16.     }
  17.    
  18.     function connectToDB() {
  19.    
  20.         $conn = mysql_connect("localhost", "blah", "blah", "monkeys");
  21.         mysql_select_db("ilikemonkeys");
  22.    
  23.     }
  24.    
  25.     function makeStringSafe($string) {
  26.    
  27.             if (!get_magic_quotes_runtime()) // if magic quotes is off
  28.                 $newstr = mysql_real_escape_string($string); // escape string
  29.    
  30.             else    // otherwise magic quotes has done the job
  31.                 $newstr = $string;
  32.    
  33.    
  34.             return $newstr;
  35.    
  36.     }
  37.    
  38.     function helloWorld() {
  39.    
  40.         connectToDB();
  41.    
  42.         $q = mysql_query("select * from monkeytable order by monkeyid desc limit 1;") or die ("failed");
  43.    
  44.         $r = mysql_fetch_assoc($q);
  45.    
  46.         echo $r['monkeyid'];
  47.    
  48.    
  49.     }
  50.  
  51.  
  52. }; // end class
  53.  
  54. ?>

Wow! So, how do we actually utilise this code elsewhere.

Instantiatatatate-ing

To use this, we need to create a new 'instance' of our class. If you're not familiar with this term already, think of a class for a cat (a domestic one, if you please). With just the class, we have a definition of what a cat looks like, and we have some functions of things cats can do (it can meow).

But we don't have a cat until we create an instance of this cat.

Likewise - we have the definition of all the stuff we can do with our DB, but we don't have an 'object' we can use until we make a new instance (or instantiate it). We need to make a new variable and use the new keyword to do this.

Provided you've included or required the file where your class is (if it's separate) then just do this:

PHP:
  1. <?php
  2. $dbobject = new dbIO;
  3. ?>

Now, we have access to all the functions (and variables, but I'll look at them later) in this class.

Let's call checkEmailAddress() and pass it in an email address, shall we?

PHP:
  1. <?php
  2. $dbobject = new dbIO;
  3.  
  4. $dbobject->checkEmailAddress("this.is@valid.com");
  5. ?>

As you can see, we use the -> notation to say to PHP "go into the instance of the class pointed to by $dbobject, and find the checkEmailAddress() function".

This doesn't do anything useful yet, as at the moment we're simply chucking away the returned result from our email address checking function, but now you've got this, you're somewhat there. At least you can use the 'organising functions' purpose of classes, anyway.

In Part 2, I'll be looking at variables inside our classes, passing data between functions inside the class and getting variables from outside.

So, until then, enjoy!

Icon from Oxygen icon set, CC BY-NC 2.5.

One Comment

  1. Alan Gilmore wrote:

    Interesting. Show me more!

    Thanks
    Alan

    Friday, October 17, 2008 at 2:57 pm | Permalink | Posted in Internet Explorer 7.0 on Windows XP

One Trackback/Pingback

  1. RambleOn » Why I never considered myself a programmer on Saturday, December 16, 2006 at 1:57 am

    [...] Peter does have a tutorial on OOP in PHP, perhaps I’ll read that and see if I can start to understand this newfangled “programming” thing. [...]

Post a Comment

Your email address is not made public or shared. Required fields are marked with *.
*
*
*
Posting a comment signifies you accept the privacy policy.
Please note - usually your comment will appear straight away but sometimes it will be held for approval (this is due to the spam filter). If your comment is waiting to be approved, please don't post it again! It will appear eventually.