PHP Object Oriented Programming

I was a pretty decent coder for the most part, but have always been intrigued with making my code more efficient and streamline. I knew how to write functions to simplify my code, but just recently I came across classes, and realized that object oriented programming could simplify my code even more.

What is Object Oriented Programming (OOP)?

OOP refers to the ability to make objects and reuse them. This begs the question, what is an object? Well, anything can be an object. What objects do you see in front of you? A computer, a television, a door, a wall? All these are objects. Think of the properties that define these objects. We will use a computer as an example.
A computer has a screen, an power button, keys, and a mouse.
A when working with a computer you have “functions” you use continually, typing keys, moving a mouse, pushing a button, displaying the results of the key push, mouse movement, etc.
We could get more specific even. Your computer has an nVidia Graphics Card, or speakers, or a screen dimmer, things that not EVERY computer would have. So you not only have all the basic properties of the computer, but you have additional properties and functions as well.
This, in a nutshell, is object oriented programming. You create an object, you give it functions and variables. You then can create several of them in just a couple of seconds, all with different properties.

How do I do it?

Now on to the fun stuff. Every programmer does it a bit differently. I create a new PHP file with the format “classClassName.php” and include that in every php script I use that needs that object. Creating a class is as simple as:

1
2
3
4
5
6
7
8
<?php
class MyClass{
   var $myVariable;
   function myFunction($value){
      $this->MyVariable =$value;
   }
}
?>

Lets examine this.

  • Line 2 shows the name of the class which I entitled “MyClass”. You can name your class anything you want, and typically it should be related to your object. If I wanted to create a class that filled in table info in HTML, I would maybe call it class Table or something.
  • Line 3 creates a variable called $MyVariable. It doesn’t have a default value and as we keep on reading, we will see that function we created can be used to set that value.
  • Line 4-6 is our function that exists to set the variable $MyVariable. This is the first time, probably, you have seen “$this->” in a PHP script. What is $this? $this is our class. This class. The “arrow” as I call it, specifies the part of the class you are calling or setting. If you had another function and wanted to call it from inside our function, you would use $this->anotherfunction(); to call it.
    This function that we have sets the variable $MyVariable to whatever value was passed. It could be a character, a number, a true/false, a sentence, you name it. That’s all it does.

Ok, so now you are asking, why the hell would I write 7-8 lines of code to set a stupid variable? I agree, it isn’t worth it. You would NEVER use a class to set a single variable that you could just as easily do without a class. This is just to demonstrate the basics.
So lets kick it up a notch and make something useful. I said the class Table previously, and that is something that I despise doing in HTML, especially large tables, so lets simplify it with a class.
First, what variables do tables have?

  1. Number of rows
  2. Number of columns
  3. Cell data

So lets plan this out:

1
2
3
4
5
6
7
<?php
class Table{
   var $NumRows;
   var $NumCols;
   var $CellData = array();
}
?>

What functions should we have?

  1. Enter data into cells
  2. Draw table
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<?php
class Table{
   var $NumRows;
   var $NumCols;
   var $CellData = array();
   function EnterData($row,$col,$data){
      $this->CellData[$row][$col]=$data;
   }
   function DisplayTable(){
      echo "<table>";
      foreach($this->CellData as $rowdata){
         echo "<tr>";
         foreach($rowdata as $celldata){
            echo "<td>".$celldata."</td>";
         }
         echo "</tr>";
      }
      echo "</table>";
   }
}
?>

There you have it, a simple class that takes the strain out of drawing a huge 20×20 table. So how do we implement it? Up til now we have been focusing on creation of the class, lets use it now!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<?php
include("classTable.php");
$table=new Table;
$table->NumRows=3;
$table->NumCols=3;
$table->EnterData(1,1,"Name:");
$table->EnterData(1,2,"Sex:");
$table->EnterData(1,3,"Age:");
$table->EnterData(2,1,"Bob");
$table->EnterData(2,2,"Male");
$table->EnterData(2,3,"33");
$table->EnterData(3,1,"Ann");
$table->EnterData(3,2,"Female");
$table->EnterData(3,3,"23");
$table->DisplayTable();
?>

Display:

Name: Sex: Age:
Bob Male 33
Ann Female 23

Ok, lets make it a little more complicated. Maybe table width, table height, table style.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
<?php
class Table{
   var $NumRows;
   var $NumCols;
   var $CellData = array();
   var $TableWidth;
   var $TableHeight;
   var $TableStyle;
   function EnterData($row,$col,$data){
      $this->CellData[$row][$col]=$data;
   }
   function DisplayTable(){
      echo "<table width='$this->TableWidth' height='$this->TableHeight' style='$this->TableStyle'>";
      foreach($this->CellData as $rowdata){
         echo "<tr>";
         foreach($rowdata as $celldata){
            echo "<td>".$celldata."</td>";
         }
         echo "</tr>";
      }
      echo "</table>";
   }
}
?>

We can get more and more indepth, and ultimately, it will make your table simpler and simpler to define and draw. Now I hope you are seeing that this can save you a little work. Think about if you had to dynamically alter a table based on info from a database… this type of thing would make it way easier.

What else?

Well there is always more to learn. Like I said at the very beginning, every computer has basic functions, but your computer may be a little more specialized. Objects in PHP are the same. You can have a parent object with a set of functions and variables, and a child class who inherits (just a like a human child inheriting features of the parent) all the variables and functions of the parent, and can have more variables and functions of their own. Here is a simple example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<?php
class First{
   var $FirstNum=1;
   var $SecondNum=2;
   var $ThirdNum;
   function AddThem(){
      $this->ThirdNum=$this->FirstNum+$this->SecondNum;
   }
}
class Second extends First{
   var $FourthNum;
   function AddAgain($value){
      $this->AddThem();
      $this->FourthNum=$this->ThirdNum+$value;
   }
}
?>

So class Second has all the variables that class First has, and then it adds an extra variable and another function.
Why do I need this? Well every page, database, feature, is going to have something just a little different. The whole purpose of programming a class is to make a “backbone” or “skeleton” and allow the programmer to code all the additional features. If your class is too specific, you may not be able to apply it more than one feature in your website. But if you keep it loose and basic, you can code additional features that are more specific, that do the job exactly as you had planned.

Private Variables?

This is something new I learned when learning about classes. I had always seen public/private variables and functions, but what were they?
Well like the name suggests, public variables/functions are accessible by everyone! And private variables are only accessible through specific class functions.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<?php
class MyClass{
   var $First;
   private $Second;
   public $Third;
   function Hello(){
      echo "Hello World";
   }
   private function Goodbye(){
      echo "Good Bye!";
   }
   public function GoodAfternoon(){
      echo "Good Afternoon!";
   }
   function AccessGoodbye(){
      $this->Goodbye();
   }
   function ChangeSecond($value){
      $this->Second=$value;
   }
}
?>

This is as basic as I can make it. Declaring a variable with var is essentially the same as making it public. If a function or variable is private it can only be accessed inside the class. I would not be able to type $myclass->Second=”this value”; because it is private! I would not be able to access a private function by using $myclass->Goodbye(); because it is private! There has to be a public function set up that allows that calls/modifies the private variables from within the function itself.
This begs the question, WHY?!? Well if you need a variable formatted a specific way, you can’t just trust a user to enter the right info 100% of the time. So rather than passing $myclass->Second=$_POST['data'];, you would send the data through a function that cleaned it up, parsed it a certain way, and after all was said and done, saved it as our all important variable.
The same thing goes for a function. You wouldn’t want a someone to send data into a function that could mess up the entire set of variables for the class. You want to make sure the data is properly formatted first by passing it through one function, then send it on its way to the private function.

Class do make everything easier. I have posted an IRC Bot class that utilizes everything we have talked about here to connect to an IRC network. Before it was a class, my code was about the same size, but was a mass of If/Then/Else statements and While loops. If I wanted to make one a quote bot, and another a help bot, and another a joke/game bot, I would have had to scrap tons of it and recode it all over again. But because it is a class, I just need to include the basics, create the commands, and viola! I have a new bot. Take a look at it here!

Views: 1230
Comments (6) Trackback Leave a comment
  1. Raju
    August 3rd, 2009 at 09:44 | #1

    A good starting point for classes. Please continue with more details with examples say an employee in a HR database, and how to evolve that object.

  2. pyr0t3chnician
    August 4th, 2009 at 11:55 | #2

    I will put up a post later today that covers a little more about this, and will hopefully answer your question.

  3. Naresh
    August 28th, 2009 at 01:27 | #3

    very nice way to explain the OOPS concepts Thanks

  4. william
    October 10th, 2009 at 21:24 | #4

    In the first snippet, the purpose of myFunction is to act as a setter for $myVariable right? Shouldn’t line six be$this->myVariable=$value;

  5. pyr0t3chnician
    October 11th, 2009 at 14:48 | #5

    Nice catch. Thanks! I got it fixed.

  6. codemaster5150
    November 21st, 2009 at 02:02 | #6

    however wrote this article did a great job.

Allowed tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="">
Trackbacks (0 ) Detail Trackback