Tutti qui dovrebbe conoscere le 'o' statemens, di solito incollati a un die() comando:PHP: errore "o" sull'istruzione fallita: come lanciare una nuova eccezione?
$foo = bar() or die('Error: bar function return false.');
La maggior parte delle volte si vede qualcosa di simile:
mysql_query('SELECT ...') or die('Error in during the query');
Tuttavia, Non riesco a capire come funziona esattamente questa affermazione "o".
vorrei lanciare una nuova eccezione invece di morire(), ma:
try{
$foo = bar() or throw new Exception('We have a problem here');
non lavorare, e nessuno dei due
$foo = bar() or function(){ throw new Exception('We have a problem here'); }
L'unico modo che ho trovato per farlo è questa orribile pensato:
function ThrowMe($mess, $code){
throw new Exception($mess, $code);
}
try{
$foo = bar() or ThrowMe('We have a problem in here', 666);
}catch(Exception $e){
echo $e->getMessage();
}
Ma c'è un modo per lanciare una nuova eccezione direttamente dopo l'istruzione "o"?
O questo tipo di struttura è obbligatoria (I dont liek la funzione ThrowMe a tutti):
try{
$foo = bar();
if(!$foo){
throw new Exception('We have a problem in here');
}
}catch(Exception $e){
echo $e->getMessage();
}
Edit: quello che voglio è proprio quello di evitare l'uso di un caso() controllare ogni potenziale un'operazione pericolosa che faccio, per esempio:
#The echo $e->getMessage(); is just an example, in real life this have no sense!
try{
$foo = bar();
if(!$foo){
throw new Exception('Problems with bar()');
}
$aa = bb($foo);
if(!$aa){
throw new Exception('Problems with bb()');
}
//...and so on!
}catch(Exception $e){
echo $e->getMessage();
}
#But i relly prefer to use something like:
try{
$foo = bar() or throw new Exception('Problems with bar()');
$aa = bb($foo) or throw new Exception('Problems with bb()');
//...and so on!
}catch(Exception $e){
echo $e->getMessage();
}
#Actually, the only way i figured out is:
try{
$foo = bar() or throw new ThrowMe('Problems with bar()', 1);
$aa = bb($foo) or throw new ThrowMe('Problems with bb()', 2);
//...and so on!
}catch(Exception $e){
echo $e->getMessage();
}
#But i'll love to thro the exception directly instead of trick it with ThrowMe function.
Forse intendevi '$ foo' nel tuo ultimo blocco di codice? –
Mi spiace, sì ... il mio male – Strae