views:

90

answers:

4

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.

+1  A: 

no, you will either have to

  • use if/else statements with error handling or
  • write a wrapper which throws exceptions or
  • use class library/framework for that

i would go for #1

henchman
+4  A: 

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";
}
?>
Urda
A: 

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.

stereofrog
+2  A: 

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.

Kris
The error handler runs at the top of the stack, outside the scope of his (or any other) try {} block. The only way to catch that exception would be with a custom exception handler. Regardless, if you want this behavior, there's already a PHP class for it -- no need to roll your own: http://www.php.net/manual/en/class.errorexception.php
Frank Farmer