An Introduction to Object Oriented Programming

on Sat Jul 05 08:33:33 GMT 2008 in PHP and viewed 3426 times

How to use PHP’s object oriented capabilities and build more sophisticated applications.


OOP is a very useful concept in PHP. It basically makes a template which one can use over and over, and extend it, there’s many different uses for it. Now it could be done just as easily with regular procedural programming, but OOP is so much better. And it makes you seem advanced.

Classes are the basic building block in OOP. It’s almost like a function. But totally different. It’s basically initiated by saying:


  class MyClass {

  }

There you go. Your own class.

This basically is a template. One can put variables and functions in it, and everything will work. These classes can be used and re-used over and over again. Variables and functions are pretty easy to add.


  class MyClass {
  var $myvar; //Creates a variable
  function myFunction(/*paramaters go here*/){
  //more stuff
  }
  }

That’s basically a class. So if I wanted to use the class, I would instantiate it. This is easily done by:


  class MyClass{

  }
  $class = new MyClass;

There. You can now access all the parts of MyClass by using the $class variable. So for example, if I wanted to print something to the screen by using classes:


  class MyClass{
  function PrintToScreen(state){
  echo $this->$state;
  }
  }

I can then say (in the same script):


  $class = new MyClass;
  $words = "Hi";
  $class->PrintToScreen($words);

It should print “Hi” to the screen. Now if you wanted to, say, alter a variable through classes, it would be done by:


  class MyClass {
  var $statement;
  function PrintToScreen(){
  echo $statement;
  }
  }
  $class = new MyClass;
  $class->$statement = "hi";
  $class->PrintToScreen();

Would print “hi”. That’s a basic introduction to classes.

There’s more advanced things to do with OOP, some of which I will cover in another article.