A Beginner’s Crash Course into Object Oriented Programming

The purpose of this article is to give a novice programmer the basic idea of what OOP is, as implemented using PHP. Readers should have a basic knowledge of programming ie what variables are, variable types, basic methods of writing comments, and how to enter code into a text editor.

Also, other programming languages will most certainly use different keywords and methods of doing things (like defining a class, labeling a variable, etc). Remember to look for the concepts in this article, and not to get caught up with semantical details.

To begin, it is important to stress that one of the core ideas behind OOP is that code written by the programmer is placed in reusable chunks. Reusable chunks of code save the developer time and money during the coding process, as well as making the code much more efficient. These reusable chunks of code are then used to create what we call an object; the object can be manipulated, made to do things, etc.

Before you actually “create an object,” you design the template for the object. This template is called a “class.” All code that the object does, and properties of the object are placed inside the class. As mentioned previously, I’ll be using PHP for demonstration purposes, as it is one of the quicker and easier coding languages to learn. Below is some sample code, which simply creates a class called “Student”:

PHP Code:<pre>
&lt;?php
class Student {

}
?&gt;</pre>

The name of our sample class is “Student.” Classes are recognized in php by the “class” keyword. What we want to do is create the template for a typical “student.” The student can do things. Some of the things the student can do include: go to class, skip school, go to lunch, turn in homework, ride the cheesewagon (er bus), that sort of thing. Anything we want the typical student to be able to do, we put inside what is called a “function” (some languages call these “methods”, ie Java).Continuing with our example:

PHP Code:

<?php 
class Student { 

   function goToClass() { 
   } 

   function rideTheBus() { 
   } 

   function skipSchool() { 
   } 
} 
?> 

Ok great. Now our template has some basic actions that our student can perform. We don’t actually have the code inside of our functions, but we’ve created the functions.

Another thing that we want to give objects are properties. Every property we want assigned to the student is also placed inside the class. Properties might include the student’s name, their grade level, their gender, their schedule, etc. On to the example:

PHP Code:

<?php 
class Student { 

   var $Name;
   var $Gender; 
   var $GradeLevel; 
   var $Schedule; 

   function goToClass() { 
   } 

   function rideTheBus() { 
   } 

   function skipSchool() { 
   } 
} 
?> 

Before continuing, I want to stress the importance of two definitions: instantiation and initialization.

Instantiation is when you actually create an object in your code. Remember that classes are templates, or definitions for objects, very similar to blueprints. Blueprints aren’t the actual house, but the design for the house. Instantiation is when you actually build the house in your code (or in this case, you create your student).

Initialization is when you first assign a value to a variable. I mention this definition here because novice programmers can easily be confused by the differences in the two words…it certainly doesn’t help that they sound very much alike!

Ok, back to the code. We’ve created some variables in our template. Unfortunately, nothing is actually assigned to the Student object; we just have empty variables. (these variables have not been initialized). You can assign values to variables in your class using the “this” keyword. Also, if you have a function called the same thing as the class name (“Student”), then when you create an “instance” of the object in your code (ie, you create a student in your application), then that function is called automatically, as soon as you create the instance of the object. This function has a special name, called a “constructor”.

I’ll get to the example in a second. I also need to mention, that functions can take “arguments” or “parameters.” These are values that are passed into the function. The function assigns these values to variables, which it can then use and/or manipulate. The values are passed in via the parenthesis of the function. Back to our example:

PHP Code:

<?php 
class Student { 

   /* These are some of the properties */ 
   var $Name; 
   var $Gender; 
   var $GradeLevel; 
   var $Schedule; 

   /* Constructor. Called as soon as we create a student (aka "instantiate the object") */ 
   function Student($studentName, $studentGender) { 
        $this->Name = $studentName; 
        $this->Gender = $studentGender; 
   } 

   function goToClass() { 
   } 

   function rideTheBus() { 
   } 

   function skipSchool() { 
   } 
}
?>

What did we do? Well we added a constructor, and we told it to accept two parameters. These parameters are assigned the variable names of “$studentName” and “$studentGender.” Now, these two variables can only be used INSIDE THIS FUNCTION. That’s called “variable scope”. The next two lines of code say “I want to take the values passed into this function, and assign them to the object.” What does that mean? Well it means that when you create the object now, you can access $Name, and $Gender. More examples…

PHP Code:

<?php 
   include "Student.php";
   $a_student = new Student("John","Male"); 
?>

I kept it simple. The code above would be a new file, while we save the rest of our example in “Student.php” The first line just makes sure that our template (the class file) is accessible. The second line is where the magic happens. It creates a new instance of the Student object, and passes two values to it – “John” and “Male”. Recall that when we create an object, the object’s “constructor” function is called immediately. Our constructor wants two values, the student name and the gender. For that reason, we passed these values in as we created the object.

You create instances of objects in PHP using the “new” keyword. The syntax is as follows:

Code:

variable = new ObjectName(parameters)

So now we have a real-code, digital student. How exciting. What do we do with him? Torture? Detention? Hmm….these all sound good, but we’ll start simply, but displaying some information about him.

PHP Code:

<?php 
   include "Student.php"; 

   $a_student = new Student("John","Male"); 
   print $a_student->Name; 
?>

Everytime you access something in an object you create (in PHP), you use the “->” characters. Some programming languages use periods. It depends on the language. (As an example, if you created that same object in JAVA, you’d print the “$Name” property by typing:

Code:

   System.out.print(a_student.Name);

(In Java, you use “System.out.print” instead of just “print”, like in php).

So we have now have a Student object. How do we make him do the things we created in our template? (ie the functions). Well once you’ve added some code to the functions, you can make the object perform those function by doing the following:

PHP Code:

<?php 
   include "Student.php"; 
   
   $a_student = new Student("John","Male"); 
   print $a_student->Name; 

   $a_student->goToClass(); 
?>

That last line tells the Student object to call the function goToClass(). Poor John. I’m certain he doesn’t want to go class. Now where’s the benefit of the function? Recall that OOP gives us access to reusable chunks of code. What if you wanted to create lots of students? An example:

PHP Code:

<?php 
   include "Student.php";

   $a_student = new Student("John","Male"); 
   $b_student = new Student("Mary","Female"); 
   $c_student = new Student("Larry","Female"); 

   print $a_student->Gender; 
   print "<br>"; 
   print $b_student->Gender; 
   print "<br>"; 
   print $c_student->Gender . " " . $c_student->Name; 

?>

That code creates 3 students. It then prints out the first two student’s genders. It then prints the third student’s Gender and his…er….her name. (I blame that on Winamp…Culture Club just started playing…..) Are you starting to see some of the benefits? You could then make b_student goToClass, and maybe have c_student skipSchool. These are spiffy things your program can do. Of course, you could write a “changeGender()” function…which seems to be particularly appropriate in the case of Larry…. It might look something like this (remember that this is a “Student” function, so this code goes inside the class. Also note that when I put ‘…’ before and after code, it means code exists before and after, but I’m not going to retype it all. Just stick this function somewhere inside your class, maybe after the skipSchool() function.)

PHP Code:

 ... 
   function changeGender() { 
      if ($this->Gender == "Female") { 
         $this->Gender = "Male"; 
      } else { 
         $this->Gender = "Female"; 
      } 
   } 
 ...  

Hehe. Place that code in the class, and whenever you want to perform a sex change in your main code, just do something similar to the following:

PHP Code:

.. 
   $a_student->changeGender(); 
..  

Now, any function can accept parameters, you just add that to the class, and then when you call the functions, you pass the values in. Let’s say we were to rewrite our “rideTheBus()” function to the following:

PHP Code:

 ... 
   function rideTheBus($busNumber) { 
      $statement = $this->Name . " rides bus number " . $busNumber; 
      return $statement; 
   } 
 ... 

then in your main program code:

PHP Code:

.. 
   print $a_student->rideTheBus("65"); 
..  

So what did we do? well in the rideTheBus() function, we told it to accept a value, and place it into the variable $busNumber. We then created a statement that says the student’s name, followed by the words “rides bus number” and then the value placed in $busNumber. The return statement says that when that function is called, return the value in $statement to whatever called the function. We then passed bus number “65” into the function. The result of the above code would be to print out the following:

John rides bus number 65.

Now, there are other ways of printing the results of the function. In our main code, we said “print the value RETURNed by the function rideTheBus(). We could have done this:

PHP Code:

.. 
   $busRideStatement = $a_student->rideTheBus("65"); 
   print $busRideStatement; 
..  

This code does the same thing, but first dumps the sentence into the $busRideStatement variable, so we could reuse it later by just calling the variable, rather than having to recall the function. The complete code of what we did is below:

File: Student.php
PHP Code:

<?php 
class Student { 

   /* These are some of the properties */ 
   var $Name; 
   var $Gender; 
   var $GradeLevel; 
   var $Schedule; 

   /* Constructor. Called as soon as we create a student */ 
   function Student($studentName, $studentGender) { 
      $this->Name = $studentName; 
      $this->Gender = $studentGender; 
   } 

   function goToClass() { 
   } 

   function rideTheBus($busNumber) { 
      $statement = $this->Name . " rides bus number " . $busNumber; 
      return $statement; 
   } 

   function skipSchool() { 
   } 

   function changeGender() { 
      if ($this->Gender == "Female") { 
         $this->Gender = "Male"; 
      } else { 
         $this->Gender = "Female"; 
      } 
   } 
}
?> 

File: index.php
PHP Code:

<?php 
include "Student.php"; 

$a_student = new Student("John","Male"); 
$b_student = new Student("Mary","Female"); 
$c_student = new Student("Larry","Female"); 

print $a_student->Gender; 
print "<br>"; 
print $b_student->Gender; 
print "<br>"; 
print $c_student->Gender . " " . $c_student->Name; 

print $a_student->rideTheBus("65"); 

$c_student->changeGender(); 
print $c_student->Gender; // this will print "Male" now... 

?> 

That is the basics of OOP in a nutshell. The terms you should be familiar with include: parameters, functions, class, constructor, variable scope, return statements, instantiation, initialization.

Again allow me to reiterate that this article/tutorial is by no means comprehensive. Some advanced topics include: passing by reference, destructors – (just a special function, called when you destroy your object), polymorphism, inheritance, and default values. I am also quite sure there are other terms I’m not remembering right now, but the basics of how OOP works is all there.

I hope that for the novice programmer interested in learning the concepts of OOP, I’ve generally explained some of the basics. Remember that if you’re programming in a language other than PHP, the core concepts of OOP are still the same! You sill create reusable chunks of code, pass values to functions, and access properties of your objects. I’d like to encourage you to try writing a sample class of your own, and creating your own objects. It is your code, you can do whatever you want! I created a female student named Larry and was able to quickly give him a sex change…try doing that in real life! For those interested in using the php example I’ve created above, but don’t know how to get started using php, I highly recommend heading over to www.php.net . Windows users may also wish to take a look at www.firepages.com.au , where a very nice man has taken the time to bundle everything in an easy-to-use zip file, so you can get started coding quickly, without the hassle of setting up PHP. On that note, I shall throw away my now empty bottle of Mt. Dew, close trusty winamp, and bid you, the reader, adieu.

About the Author:
John Collins has been writing code for almost 20 years, since he was 5 years old writing in BASIC on his Commodore64. He enjoys coding, sports, and reading. He currently serves as lead developer, webmaster, and computer technician for a school division in Virginia, USA.


If you would like to see your thoughts or experiences with technology published, please consider writing an article for OSNews.

57 Comments

  1. 2004-04-21 6:47 am
  2. 2004-04-21 7:00 am
  3. 2004-04-21 7:06 am
  4. 2004-04-21 7:25 am
  5. 2004-04-21 7:26 am
  6. 2004-04-21 8:00 am
  7. 2004-04-21 8:05 am
  8. 2004-04-21 10:08 am
  9. 2004-04-21 10:19 am
  10. 2004-04-21 11:39 am
  11. 2004-04-21 11:54 am
  12. 2004-04-21 12:23 pm
  13. 2004-04-21 12:48 pm
  14. 2004-04-21 12:57 pm
  15. 2004-04-21 1:06 pm
  16. 2004-04-21 1:14 pm
  17. 2004-04-21 1:31 pm
  18. 2004-04-21 1:57 pm
  19. 2004-04-21 2:04 pm
  20. 2004-04-21 2:24 pm
  21. 2004-04-21 2:37 pm
  22. 2004-04-21 2:47 pm
  23. 2004-04-21 2:58 pm
  24. 2004-04-21 3:08 pm
  25. 2004-04-21 3:56 pm
  26. 2004-04-21 4:09 pm
  27. 2004-04-21 4:10 pm
  28. 2004-04-21 4:26 pm
  29. 2004-04-21 4:45 pm
  30. 2004-04-21 4:48 pm
  31. 2004-04-21 4:53 pm
  32. 2004-04-21 5:08 pm
  33. 2004-04-21 5:14 pm
  34. 2004-04-21 5:39 pm
  35. 2004-04-21 5:49 pm
  36. 2004-04-21 6:40 pm
  37. 2004-04-21 6:42 pm
  38. 2004-04-21 6:49 pm
  39. 2004-04-21 8:25 pm
  40. 2004-04-21 8:39 pm
  41. 2004-04-21 8:58 pm
  42. 2004-04-21 9:12 pm
  43. 2004-04-21 9:26 pm
  44. 2004-04-21 9:27 pm
  45. 2004-04-21 9:48 pm
  46. 2004-04-21 11:32 pm
  47. 2004-04-21 11:35 pm
  48. 2004-04-22 2:40 am
  49. 2004-04-22 5:44 am
  50. 2004-04-22 11:19 am
  51. 2004-04-22 11:30 am
  52. 2004-04-22 1:05 pm
  53. 2004-04-22 2:29 pm
  54. 2004-04-22 3:40 pm
  55. 2004-04-22 4:17 pm
  56. 2004-04-22 8:18 pm
  57. 2004-04-23 5:22 am