Hi guys :)
Most functions in PHP returns true/false:
var_dump (is_int ("1")); // false
Can I configure PHP to return exceptions instead of boolean ?
try {is_int ("1")} catch (Exception $e) {exit ($e->getMessage ());}
Thanks.
Hi guys :)
Most functions in PHP returns true/false:
var_dump (is_int ("1")); // false
Can I configure PHP to return exceptions instead of boolean ?
try {is_int ("1")} catch (Exception $e) {exit ($e->getMessage ());}
Thanks.
no, you will either have to
i would go for #1
Couldn't you just use a throw?
<?php
function myFunction($var)
{
if(!(is_int($var))
{
throw new Exception('Custom message about the error');
}
}
?>
And the just have a try/catch block to catch your issue?
<?php
try
{
myFunction(1);
myFunction("1");
}
catch
{
echo 'Caught exception: ', $e->getMessage(), "\n";
}
?>
i guess you mean functions that return false and generate a warning on failure, like fopen(). Yes, you can (and actually should) convert these warnings to exceptions, using the technique outlined here.
I agree is_int
would be a terrible thing to throw an exception, but you could change warnings and errors into exceptions by settint an error handler that'll throw an exception with the warning or error message:
class ErrorOrWarningException extends Exception
{
protected $_Context = null;
public function getContext()
{
return $this->_Context;
}
public function setContext( $value )
{
$this->_Context = $value;
}
public function __construct( $code, $message, $file, $line, $context )
{
parent::__construct( $message, $code );
$this->file = $file;
$this->line = $line;
$this->setContext( $context );
}
}
function error_to_exception( $code, $message, $file, $line, $context )
{
throw new ErrorOrWarningException( $code, $message, $file, $line, $context );
}
set_error_handler( 'error_to_exception' );
Not that this will not magically change non errors to throw exceptions the way you explained it, but I believe it may be just what you're looking for.