Exceptions in native PHP functions

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.

Answers


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 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.


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


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.


Need Your Help

Datetime field in RKPaginator URL

ios objective-c restkit restkit-0.20 sockit

I am using RestKit and I am trying to use the RKPaginator. However, I need to have a datetime field within the URL Request. I am building the following requestString, which is a NSString, and use i...

Can not deploy django using gunicorn and supervisor

django gunicorn django-deployment

I'm trying to deploy a django project using gunicorn/nginx as webserserver. The project works perfectly fine when I just run this command in virtualevn: