4.1 Working with File Constants


You need to create an error-reporting function that reports errors and gives both the name of the file where the error occurred and the line of the file.

Technique

Use the __FILE__ and __LINE__ constants to obtain this information:

 <?php require_once 'DB.php'; function ferror($file,                 $line,                 $message='General Error') {     $errmsg = "There was an error in script $file, on $line: $message\ n";     error_log($errmsg);     die('An error occurred, it has been logged in the system log'); } $dbh = DB::connect("mysql://user:secret@localhost/dbname"); if (!$dbh) {     $dbh = ferror(__FILE__,__LINE__, sprintf('[%d]: %s',                   $dbh->getCode(), $dbh->getMessage()); } // Database connection stuff here ?> 

Comments

The function itself should be pretty self-explanatory. It takes the arguments $file , $line , and $message from the user and prints them out with some formatting so that the error message is a little more readable. We also assign a default value for $message so that we may omit the $message argument when calling the function. For example, calling ferror() like so:

 ferror(__FILE__,__LINE__) 

is completely legal. The new code is when we actually call ferror() using the predefined __FILE__ and __LINE__ constants to give the current file and current line. The __FILE__ and __LINE__ constants are documented as such in the PHP manual:

__FILE__

The name of the script file presently being executed. If used within a file which has been included or required, then the name of the included file is given, and not the name of the parent file.

__LINE__

The number of the line within the current script file which is being executed. If used within a file which has been included or required, then the position within the included file is given.



PHP Developer's Cookbook
PHP Developers Cookbook (2nd Edition)
ISBN: 0672323257
EAN: 2147483647
Year: 2000
Pages: 351

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net