6th Oct, 2008 - 02:47:01 PM
IF YOU PLAN ON USING THIS WEBSITE PROPERLY, THEN PLEASE ENABLE JAVASCRIPT IN YOUR BROWSER.

YOU WILL NOT FIND ANY MALICIOUS SCRIPTING ON THIS WEBSITE.

YOUR BROWSING EXPERIENCE WILL BE SEVERLY HAMPERED IF YOU DO NOT ENABLE JAVASCRIPT BEFORE CONTINUING.

YOU WILL CONTINUE TO SEE THIS MESSAGE UNTIL YOU ENABLE JAVASCRIPT.
Your are currently not logged in. ( Login / Register )
NAME:   Introduction to OOP
AUTHOR:   punkstar
DATE:   21st Feb, 2006 - 03:59:28 AM
DESCRIPTION:   What is Object Orientated Programming, and why even bother using it?

Need some help with that coding?


Most programming good programming languages out there support classes inherently, c++, c#, java etc.. and php does have support for these also. But what will going OOP do for your code and your systems. Well to see this, lets have a look at an easy php class.

PHP Code
<?php
class ima {
  var 
$variable1;
  var 
$variable2;
  
  function 
setVariable($varname$value) {
    $
$varname $value;
  }

  function 
echoVariable($varname) {
    echo $
$varname;
  }
}
?>


..and there we have it, a simple class. It actually doesn't do much, but how on earth do we start using that in our code? Firstly, we need to create an instance of the class, that is to make the class start working. So we use the name of the class, which is ima in this case, and put it in this code:

PHP Code
<?php
$varClass 
= new ima;
?>


Now the variable varClass is our access point to the contents of the class. Accessing class variables and class methods (functions) are demostrated below, again.. its very simple. Its just the syntax that you need to learn.

PHP Code
<?php
//start the class
$varClass = new ima;

//echo a variable
echo $varClass->variable1;

//echo a function
echo $varClass->setVariabel("variable1",12312);
?>


Now thats all very well and good, but how on earth is this going to help me in my coding you may be asking? Well in simplest terms, you can cut down on your coding ten fold. On the old IMA site, I had mysql_query() everywhere I needed to make a query, now all I need is $db->query(), and then all the lines of code that I would have needed to write after that have been condensed into $db->num_rows(); (no need for link identifiers), then $db->next_record(); etc.

So when I am coding inside a class, how can I get at the variables etc? Can I get at external variables?

PHP Code
<?php
class funky {
  var 
$variable "123";
  
  function 
__echo() {
    echo 
$this->funky;
  }
}
?>


As you can see, its the same as how you would do it if you were outside the class, but you use the $this variable, instead of the class name.

..and you cannot get at external variables from inside a class. A class is meant to be a module of code that can be easily transferrable, so dependancies on outside code is not accepted.

PHPClasses.org is a great resource for free online php classes!

Peace.