Re: Setting the line number for debugging

[email protected] ("Sean McCann") Wed, 14 Aug 2002 09:31:07 -0500
Newsgroups php.lang
Message-ID <[email protected]>
> Is it possible to set the line number and file name to show in error
> messages?

Yes.

> I'm looking for something similar to the perl's expression
>     #line 298 myscript.pl
> which tells the compiler explicitely that here is line 298 of myscript.pl.
> If an error occurs 5 lines later, it would show something like "compile
> error at line 303 in myscript.pl", whatever the real line number and
> filename is.
> Thomas
> [email protected]

There are two special variables in PHP: __LINE__ and __FILE__ that
accomplish this (note that there are 2 underscores before and after the
words LINE and FILE).  __LINE__ doesn't work quite like the aforementioned
#line in Perl, but it can still be used to output error messages with an
actual script line number.  Keep in mind that __LINE__ always gives you the
line number of the file where __LINE__ appears.  __FILE__ gives you the full
path and filename of the script as it is seen on the server.  If you just
want the actual name of the file, you should try calling basename().

An example of using __LINE__ and __FILE__ :

if (! $link = @ mysql_connect($host,$username,$password) ){
    some_error_reporting_function(__LINE__-1,basename(__FILE__));
    // Outputs: "Could not connect to MySQL database on line 5 of
'script.php'."
}


Not the best example, since it doesn't use the built-in PHP error handling
functions, and it has a hardcoded "-1", but it works.

 - Sean
[email protected]