2014-10-05 6 views
5

C'è un modo per dire a PHP di generare un'eccezione quando sto tentando di accedere a un membro o un metodo su un oggetto null?PHP gestisce la gestione nulla in base all'eccezione

Es .:

$x = null; 
$x->foo = 5; // Null field access 
$x->bar(); // Null method call 

In questo momento, ho solo i seguenti errori che non sono bello da gestire:

PHP Notice: Trying to get property of non-object in ... 
PHP Warning: Creating default object from empty value in ... 
PHP Fatal error: Call to undefined method stdClass::bar() in ... 

Vorrei avere una deroga specifica invece essere gettato. È possibile?

+0

Registrare un [gestore errori globale] (http://php.net/manual/en/function.set-error-handler.php) e lanciare le proprie eccezioni. – Rob

risposta

3

È possibile trasformare i propri avvisi in eccezioni utilizzando in modo tale che quando si verifica un avviso, genererà un'eccezione che è possibile catturare in un blocco try-catch.

Gli errori irreversibili non possono essere trasformati in Eccezioni, sono progettati per fermare il phap al più presto. tuttavia siamo in grado di gestire l'errore del feto con grazia facendo qualche ultima trasformazione minuto usando register_shutdown_function()

<?php 

//Gracefully handle fatal errors 
register_shutdown_function(function(){ 
    $error = error_get_last(); 
    if($error !== NULL) { 
     echo 'Fatel Error'; 
    } 
}); 

//Turn errors into exceptions 
set_error_handler(function($errno, $errstr, $errfile, $errline, array $errcontext) { 
    throw new ErrorException($errstr, 0, $errno, $errfile, $errline); 
}); 

try{ 
    $x = null; 
    $x->foo = 5; // Null field access 
    $x->bar(); // Null method call 
}catch(Exception $ex){ 
    echo "Caught exception"; 
} 
1

aggiungere questo codice nel file che è incluso o eseguito prima di qualsiasi altra cosa:

set_error_handler(
    function($errno, $errstr, $errfile, $errline) { 
     throw new \ErrorException($errstr, $errno, 1, $errfile, $errline); 
    } 
); 
2

provare questo codice per la cattura tutti gli errori:

<?php  
$_caughtError = false; 

register_shutdown_function(
     // handle fatal errors 
     function() { 
      global $_caughtError; 
      $error = error_get_last(); 
      if(!$_caughtError && $error) { 
       throw new \ErrorException($error['message'], 
              $error['type'], 
              2, 
              $error['file'], 
              $error['line']); 
      } 
     } 
); 

set_error_handler(
    function($errno, $errstr, $errfile, $errline) { 
     global $_caughtError; 
     $_caughtError = true; 
     throw new \ErrorException($errstr, $errno, 1, $errfile, $errline); 
    } 
); 

Dovrebbe essere eseguito o incluso prima di altro codice.

È anche possibile implementare un Singleton per evitare variabili globali o lasciare che generino due eccezioni, se non vi dispiace.

Problemi correlati