» PHP Objects

By ivc at 00:03, November 8, 2008

For a long time I’ve been aware of classes (and their objects) in PHP but I’ve never really gotten the time to figure out how they work and how they’re structured, before now.

A class can have a collection of functions that belong to a specific part, or say, module of a site. Instead of having functions (function name () {}) listed alone in a file and available in the global scope, i.e include once and the function will be available till the end of the execution. A function inside a class can only be called upon by the name of the object or inherit of itself(this.).

Which brings me to objects, a class is the code that lists the available functions, but a object is a run-time instance of the class and its functions can be addressed via the name of the new instance ($db = new Mysql();). Think of object like e.g. creating a new tab in web-browser.

// Mysql class
class Mysql {
   function connect($host, $name, $pass, $db) {
      $connection = mysql_connect("$host","$name","$pass");
      mysql_select_db("$db", $connection) or die("Couldn't select database.");;
   }

   function close() {
      mysql_close($connection);
   }

   function query($query) {
      mysql_query(...);
   }
}

// Create a new instance
$db = new Mysql();

// Mysql connect
$connection = $db->connect('localhost','ivc','passwd','twitterurl');

// Send query
$db->query("SET CHARACTER SET 'utf8'");

Pretty cool and handy!

» Leave a Reply


Notice: Undefined variable: user_ID in /usr/home/ivc/public_html/sites/ivc/blog/wp-content/themes/ivc/comments.php on line 51

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>