OOP IN PHP 5

PHP5 offers some remarkable improvments for PHP programmers. This tutorial is aimed at describing what Object Orientated Programming is and how it can be utilized. Lets go over the basics.

OOP can be broken down into 3 main componants, you have classes, methods and objects. methods(also know as funcitons) live inside classes and in order to call them out, we use objects. Its as simple as that. To better understand this lets take a look at the code.

So first off we want to create a new class, this can be done like so;

<?php
//define a new class
class myClass{
}
?>

Congratulations you have created your first class! All we have done is used a reserved word class then followed it with our own unique name, in this case myClass. The next step would be to put something into this new class, for example a method;

<?php
//a class
class myClass{
  //define a funciton
  function hello(){
     $shout="hello world";
    return $shout;
  }
}
?>

Ok nothing new here, just a simple method which will echo out a variable. Now we need to get to the method inside the class, this is where the object I mentioned comes into play;

//a new object
$speak = new myClass;

This may look a little different from something you have encountered before, but its pretty straight forward, all we’re doing here is declaring a new object which has a value of our new class, this will make more sense as we go on;

//access our method
echo $speak->hello();

Here we want to access our method in our class by calling our object, so we use the -> operator to do this,

Finally put it all together and we are left with;

<?php
//a class
class myClass{
  //define a funciton
  function hello(){
    $shout="hello world";
    return $shout;
  }
}
//a new object
$speak = new myClass;
//access our method
echo $speak->hello();
?>

Its at this point you may well be wondering what the point to all this is, I mean this is nothing but a more complicated way of writting your scripts. The benefits come when you want to write more sophisticated applications, and your time spent re writting your code will pay dividence when it comes to maintaning and updating them in the future.

  • Digg
  • StumbleUpon
  • del.icio.us
  • Twitter
  • Google Bookmarks
  • email
  • Facebook
  • RSS

Talk to me