January 24th, 2007 - by cpradio

For those just joining, it is suggested that you begin with OOP in PHP from a .NET OOP Perspective as this is Part 2 of a series.

With that said, I am going to outline the base classes that I referred to in the first article. To start out I will talk about the Error class, as if you do not have a good error handling setup, your application is doomed from the beginning.

It should also be stated that the below code will only work using PHP 5.

The Error class is probably the most important class you will ever write, as any error your application needs to throw should have a standard way of taking care of it. So the basic things you will need is a way to report the error, a way to view the error(s), and a way to determine if there is an error. Likewise, I designed the Error class to also accept Warnings. Items that are not errors but should be noted as a potential hazard or caution.

  1. class Error
  2. {
  3.   ## PRIVATE VARIABLES
  4.     private static $title;
  5.     private static $type;
  6.     private static $description;
  7.     private static $datetime;
  8.     private static $numErrors;
  9.     private static $numWarnings;
  10.   ## END PRIVATE VARIABLES
  11. }

First I will start with the variables. Note that everything is marked “private static”. This simply means, all of the variables can only be accessed within the class and that their values will be kept between all instances of the class.

Now let’s discuss the variables.
$title = This is going to be an array for each Error’s Title that is thrown.
$type = This is going to be either ‘Error’ or ‘Warning’ so it designates which was thrown.
$description = This will be an array for each Error’s Description that is thrown.
$datetime = This is the error/warning date and time of when the error or warning was thrown.

These four arrays must keep in sync with each other, so every time an error/warning is logged, an element is added to each array.

$numErrors = Stores the number of errors currently logged.
$numWarnings = Stores the number of warnings currently logged.

Since the variables are now defined, lets work on the methods for the class. The first method is written to initialize all of the static variables. In layman’s terms, it’s to ensure all of the arrays start as empty and the counters start at zero.

  1. // Initialize the Variables
  2. // Does not return anything, but acts like a constructor for Static classes
  3. public static function Initialize()
  4. {
  5.   self::$title   = array();
  6.   self::$type  = array();
  7.   self::$description = array();
  8.   self::$datetime  = array();
  9.   self::$numErrors   = 0;
  10.   self::$numWarnings = 0;
  11. }

To call your method you would use Error::Initialize();. Notice that there are no variables, just the class name followed by :: and the method name. This is due to the method being static and therefore you do not have to set a variable to interact with the class.

Like any good programmer, I also write a method to clear out the variables at the end of the execution.

  1. // DeInitialize the Variables
  2. // Does not return anything, but acts like a destructor for Static classes
  3. public static function DeInitialize()
  4. {
  5.   self::$title = null;
  6.   self::$type = null;
  7.   self::$description = null;
  8.   self::$datetime = null;
  9.   self::$numErrors = null;
  10.   self::$numWarnings = null;
  11. }

Simply put, this ensures all of the variables are back to the values they started with in PHP. Hence why we wrote an “Initialize” method. Error::DeInitialize(); should ONLY be called when you are through with the errors/warnings generated by your application, otherwise, you will be wiping out all of the errors/warnings caught during execution.

Now you need ways of logging the Errors and Warnings, so those methods are as follows:

  1. // Log Error Method (receives Name and Description)
  2. // Returns true or false depending on if the logging of the error was successful
  3. public static function LogError($varTitle, $varDescription)
  4. {
  5.   // Check Parameters
  6.   if (strlen(trim($varTitle)) != 0 && strlen(trim($varDescription)) != 0)
  7.   {
  8.     array_push(self::$title, $varTitle);
  9.     array_push(self::$type, "ERROR");
  10.     array_push(self::$description, $varDescription);
  11.     array_push(self::$datetime, date("m/d/Y H:i:s"));
  12.     self::$numErrors++;
  13.    
  14.     return true;
  15.   }
  16.  
  17.   return false;
  18. }
  19.  
  20. // Log Warning Method (receives Name and Description)
  21. // Returns true or false depending on if logging the warning was successful
  22. public static function LogWarning($varTitle, $varDescription)
  23. {
  24.   // Check Parameters
  25.   if (strlen(trim($varTitle)) != 0 && strlen(trim($varDescription)) != 0)
  26.   {
  27.     array_push(self::$title, $varTitle);
  28.     array_push(self::$type, "WARNING");
  29.     array_push(self::$description, $varDescription);
  30.     array_push(self::$datetime, date("m/d/Y H:i:s"));
  31.     self::$numWarnings++;
  32.    
  33.     return true;
  34.   }
  35.  
  36.   return false;
  37. }

Just like the prior methods, calling these is no different other than you are to pass two parameters. For example, Error::LogError("Title", "Description");. Now the Error class is shaping up to take on its role, however, it needs a few more methods to put it into practice. As right now, what if we want to know if any errors/warnings have occurred? How about displaying all of the errors/warnings that have occurred? Finally, what if you only want to retrieve the last error thrown or what if you want to clear out the errors and warnings? Well, that is what the below does, and of course, feel free to extend it to your heart’s content.

  1. // Show Error Messages
  2. // Returns the Error Message Output (in HTML format)
  3. public static function ShowErrorMessages()
  4. {
  5.   $output = "";
  6.  
  7.   // Check to see if 1 error occurred or more than one.
  8.   if (self::$numErrors  > 0)
  9.   {
  10.     if (self::$numErrors  > 1)
  11.     {
  12.       $error = "ERRORS";
  13.     }
  14.     else
  15.     {
  16.       $error = "ERROR";
  17.     }
  18.    
  19.     // Loop through Error Messages
  20.     for ($i = 0; $i <  sizeof(self::$title); $i++)
  21.     {
  22.       if (self::$type[$i] == "ERROR")
  23.       {
  24.         // Output each individual Error
  25.         $output .= "  <div class=\"divErrorTitle\">\r\n" .
  26.          "  " . self::$title[$i] . "\r\n" .
  27.          "  <span class=\"spnErrorDateTime\">at " . self::$datetime[$i] . "</span>\r\n" .
  28.          "  \r\n" .
  29.          "  <div class=\"divErrorDesc\">" . self::$description[$i] . "<br /><br /></div>\r\n";
  30.       }
  31.     }
  32.    
  33.     // Write Error Template Output
  34.     $output  = "<div id=\"divErrorBox\">\r\n" .
  35.      "  <div id=\"divErrorBoxTitle\"><img src=\"designs/icons/24-em-cross.png\" align=\"left\" /> {$error}:</div>\r\n" .
  36.      "  <div id=\"divErrors\">\r\n" . $output . "\r\n  </div>\r\n" .
  37.      "</div>\r\n";
  38.   }
  39.  
  40.   // Return the Error Message Output
  41.   return $output;
  42. }
  43.  
  44. // Retrieve Last Error
  45. // Returns the title and description of the last error in an array
  46. public static function RetrieveLastError()
  47. {
  48.   $output = array();
  49.  
  50.   // Check to see if 1 error occurred or more than one.
  51.   if (self::$numErrors  > 0)
  52.   {
  53.     for ($i = sizeof(self::$title) - 1; $i >= 0; $i++)
  54.     {
  55.       if (self::$type[$i] == "ERROR")
  56.       {
  57.         array_push($output, self::$title[$i]);
  58.         array_push($output, self::$description[$i]);
  59.         break;
  60.       }
  61.     }
  62.   }
  63.  
  64.   return $output;
  65. }
  66.  
  67. // Clear Errors
  68. // Returns nothing
  69. public static function ClearErrors()
  70. {
  71.   self::$numErrors   = 0;
  72.  
  73.   for ($i = 0; $i  0)
  74.   {
  75.     return true;
  76.   }
  77.  
  78.   return false;
  79. }
  80.  
  81. // Show Warning Messages
  82. // Returns the Warning Message Output (in HTML format)
  83. public static function ShowWarningMessages()
  84. {
  85.   $output = "";
  86.    
  87.   // Check to see if 1 warning occurred or more than one.
  88.   if (self::$numWarnings  > 0)
  89.   {
  90.     if (self::$numWarnings  > 1)
  91.     {
  92.       $warning = "WARNINGS";
  93.     }
  94.     else
  95.     {
  96.       $warning = "WARNING";
  97.     }
  98.    
  99.     // Loop through Warning Messages
  100.     for ($i = 0; $i <  sizeof(self::$title); $i++)
  101.     {
  102.       if (self::$type[$i] == "WARNING")
  103.       {
  104.         // Output each individual Warning
  105.         $output .= "  <div class=\"divWarningTitle\">\r\n" .
  106.          "  " . self::$title[$i] . "\r\n" .
  107.          "  <span class=\"spnWarningDateTime\">at " . self::$datetime[$i] . "</span>\r\n" .
  108.          "  \r\n" .
  109.          "  <div class=\"divWarningDesc\">" . self::$description[$i] . "<br /><br /></div>\r\n";
  110.       }
  111.     }
  112.    
  113.     // Write Warning Template Output
  114.     $output  = "<div id=\"divWarningBox\">\r\n" .
  115.      "  <div id=\"divWarningBoxTitle\"><img src=\"designs/icons/24-message-warn.png\" align=\"left\" /> {$warning}:</div>\r\n" .
  116.      "  <div id=\"divWarnings\">\r\n" . $output . "\r\n  </div>\r\n" .
  117.      "</div>\r\n";
  118.   }
  119.  
  120.   // Return the Warning Message Output
  121.   return $output;
  122. }
  123.  
  124. // Has Warnings
  125. // Returns true or false on whether there are any Warnings
  126. public static function HasWarnings()
  127. {
  128.   if (self::$numWarnings  > 0)
  129.   {
  130.     return true;
  131.   }
  132.  
  133.   return false;
  134. }

As stated at the beginning, your application will need a way to handle errors, and maybe even warnings. The above class, is one approach and the one I use in my applications. It definitely is not the only approach, so feel free to comment on error classes you have used in your applications.

Be Sociable, Share!

6 Responses to “OOP in PHP from a .NET OOP Perspective: The Error Class”

1 Martin K

In your example you use a initialize method for your variables. I’m curious about why you don’t use the __construct method for initialization?. Or are there any drawbacks with __construct?

2 cpradio

The variables and classes are static. The constructor will not be executed, because there is no physical definition of the class. IE: $classVar = new Error();

So since the method is static, you have to use a custom method to initialize your variables, or be very cautious if you do not by adding a lot of IF statements to ensure they were initialized before using them.

The __construct method is EXCELLENT for non-static classes and should be used, however, static variables and classes are not accessible by a constructor.

3 cpradio

I should also mention, that the above comment is largely based on OOP in general. PHP’s documentation over static classes does not cover constructors and their roles in a static class.

It may be possible that PHP adequately runs the __construct method for a static class, but I am willing to bet if it does, it probably runs it with every static method call, which defeats our purpose of keeping all errors that occur on the page in one instance of the class.

4 Peter

I hardly have any experience in real-world projects with programming, but I do have programming experience, and nothing makes me more “giddy” than digging deep into OOP, your articles are invigorating and I’m enjoying refreshing my mind (I’ve been away from programming anything for a long while) Now I will enjoy coming into the world like a fresh prog. newb. Again, thank you for your contributions to the community and my brain!

5 cpradio

More than happy to help Peter. I am actually finally getting started on my next installment regarding the Design class I use in my applications.

Hopefully, what I have so far and what I plan on going into in the next installments of OOP, will give everyone a great library of classes to extend and use.

6 lonelyCoder

Hi,

I have tried to create my own “absolute” error class for my apps couple of times but always found something that just wasn’t right.

Your articles indeed helped me but I have one (maybe stupid) question regarding one of the functions..

ClearErrors – function
what is actually the purpose of that for-loop and is it correctly written on your example?


public static function ClearErrors(){
self::$numErrors = 0;
for($i = 0; $i 0)
..
..
}

Does that syntax actually work?
Haven’t tried this yet but it seems a bit odd..

Once again thank you for your effort to simplify OOP for newb’s.. Waiting eagerly your Design class…

Share your thoughts...

mulberry sale spyder womens jacket cheap new balance 574 mulberry outlet cheap new balance 574 arcteryx outlet mulberry sale spyder womens jacket mulberry sale spyder womens jacket mulberry outlet mulberry outlet new balance 574

Popular Articles

Top 10 Commentators


Subscribe to this feed! Subscribe by Email!

Random Bits Podcast

You need to download the Flash player from Adobe

Blogs Worth Reading