Greytree

TamWiki

For a mouse who is a packrat

Technology » Use Object Oriented Methods In PHP
OOP is the way to write elegant, simple code

Summary:this is what goes at the top of the site

(redirected from Main.UseObjectOrientedMethods)

OOP? is the way to go for writing clean, expressive code. Several languages support OOP concepts, including PHP, RubyOnRails, JavaScript and of course, old stand-bies like C++ and Java.

Some examples of good use of OOP

In PHP the mysqli functions for database access are expressed in an object-oriented way (they also have a procedural interface if you do choose to go that way).

Setting it up is as easy as:

  1. $db = new mysqli(DBHOST, DBUSER, DBPASS, DBNAME);

And voila! -- you've got a database connection and handle that can be used to interact with the database.

In addition, mysqli defines a result object and a statement object that give good handles on using the interface.

  1. $result = $db->query($sql_stmt);
  2. if (!$result) handle_error($db->error);
  3.  
  4. $rows = Array();
  5. while ($row = $result->fetch_assoc()) {
  6.     $rows[]=$row;
  7. }
  8. $result->free();

Now you got a sequential array of the associative array corresponding to each row in the query

Writing your own classes

The documentation at http://php.net is not too bad for how to write the syntax for classes and using them as objects, but it doesn't say anything about when to do this. In general, the deciding factor for going procedural vs. OO is somewhat arbitrary. If you have to associate data with certain functions, or if you want to keep certain areas of your application separate from other areas, OO is the way to go.

In general, the way of writing a class is to declare the class, create a constructor, and write all the public and private functions and variables for the class. Elsewhere, I talk about debugging in PHP. Here is an example of class that can be used to handle the debugging functions:

  1. class MyClass {
  2.   function __construct () {
  3.   }
  4. }

To instatiate this object, first you include it, then create a debugging object:

  1. include('MyClass.php');
  2.  
  3. $objext = new MyClass();

There are probably many, many application features that can be better encapsulated in a class, and thus preparing the way for more reuse of code?.


Tags: Categories: Articles

Recent Changes | Printable View | Page History | Edit Page
Page last modified on April 17, 2012, at 08:59 PM by ImportText?