(redirected from Main.UseObjectOrientedMethods)
On this page... (hide)
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:
- $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.
- $result = $db->query($sql_stmt);
- if (!$result) handle_error($db->error);
- $rows = Array();
- while ($row = $result->fetch_assoc()) {
- $rows[]=$row;
- }
- $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:
- class MyClass {
- function __construct () {
- }
- }
To instatiate this object, first you include it, then create a debugging object:
- include('MyClass.php');
- $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?