Wszyscy tu powinien znać „lub” statemens zwykle przyklejone do matrycy() polecenie:PHP: Instrukcja "lub" w przypadku niepowodzenia instrukcji: jak wyrzucić nowy wyjątek?
$foo = bar() or die('Error: bar function return false.');
Najbardziej czasów widzimy coś takiego:
mysql_query('SELECT ...') or die('Error in during the query');
Jednak nie mogę zrozumieć jak dokładnie działa ta "lub" instrukcja.
chciałbym rzucać nowy wyjątek zamiast matrycy(), ale:
try{
$foo = bar() or throw new Exception('We have a problem here');
robi praca, ani
$foo = bar() or function(){ throw new Exception('We have a problem here'); }
Jedynym sposobem znalazłem na to jest to straszne myśli:
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();
}
Ale istnieje sposób, aby rzucić nowy wyjątek bezpośrednio po stwierdzeniu "lub"?
Albo tego rodzaju konstrukcji jest obowiązkowe (dont liek funkcję ThrowMe na wszystkie):
try{
$foo = bar();
if(!$foo){
throw new Exception('We have a problem in here');
}
}catch(Exception $e){
echo $e->getMessage();
}
Edit: co chcę jest naprawdę, aby uniknąć korzystania z if() sprawdza każdy potencjalny niebezpieczna operacja to zrobić, na przykład:
#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.
Czy chodziło Ci '$ foo' w ostatnim bloku kodu? –
Przepraszam, tak .. mój zły – Strae