You are here: Re: Returning NULL vs. returning FALSE « PHP Programming Language « IT news, forums, messages
Re: Returning NULL vs. returning FALSE

Posted by Umberto Salsi on 11/06/35 11:32

"Thomas Mlynarczyk" <blue_elephant55@hotmail.com> wrote:

> It seems to be a generally adopted convention to have a function return
> FALSE in case of an error. But if a function is supposed to return a boolean
> anyway, one cannot distinguish anymore between the "normal" FALSE and the
> "error" FALSE. So why not using NULL instead to indicate an error? Are there
> drawbacks I am not aware of?


IMHO, the FALSE value as an error indicator is a practice that date
from the PHP 3 era, when the NULL value was not available. Today, with
PHP 4 and 5, new software (either new PHP extensions and PHP scripts)
might certainly adopt the NULL value in place of FALSE.

But instead to encode the error inside the returned value, there are
better solutions:

* using PHP 5 exceptions;

* writing your error handling function that sets a global flag on error,
something like this:


/*. require_module 'standard'; .*/

$err = FALSE;
$err_msg = "";

function my_error_handler(/*.int.*/ $type, /*.string.*/ $msg)
{
$GLOBALS["err"] = TRUE;
$GLOBALS["err_msg"] = $msg;
if( error_reporting() == 0 )
# inside "@..." - do not report the err
return;
error_log( date("m-d,H:i:s ") . $msg );
}


set_error_handler( "my_error_handler" );


/*.bool.*/ function got_err()
# An error occurred?
{
if( $GLOBALS["err"] ){
$GLOBALS["err"] = FALSE; # reset err flag
return TRUE;
} else {
return FALSE;
}
}




/*.float.*/ function div(/*.int.*/ $a, /*.int.*/ $b)
{
$GLOBALS["err"] = FALSE;
if( $b == 0 ){
trigger_error(__FUNCTION__."(): division by zero");
return 0.0;
}
return $a/$b;
}


# Unhandled error - will be logged:
$x = div(3, 0);

# Handled error - not logged:
$y = @div(3, 0);
if( got_err() )
echo "ERROR: ", $err_msg;

$f = @fopen("do-not-exists", "r");
if( got_err() )
echo "Sorry, can't open the file: ", $err_msg;
else
do that and that with $f


Regards,
___
/_|_\ Umberto Salsi
\/_\/ www.icosaedro.it

 

Navigation:

[Reply to this message]


Удаленная работа для программистов  •  Как заработать на Google AdSense  •  England, UK  •  статьи на английском  •  PHP MySQL CMS Apache Oscommerce  •  Online Business Knowledge Base  •  DVD MP3 AVI MP4 players codecs conversion help
Home  •  Search  •  Site Map  •  Set as Homepage  •  Add to Favourites

Copyright © 2005-2006 Powered by Custom PHP Programming

Сайт изготовлен в Студии Валентина Петручека
изготовление и поддержка веб-сайтов, разработка программного обеспечения, поисковая оптимизация