|
 |
PHP поддерживает один оператор управления ошибками: знак @.
В случае, если он предшествует какому-либо выражению в PHP-коде, любые
сообщения об ошибках, генерируемые этим выражением, будут проигнорированы.
В случае, если установлена опция track_errors,
все генерируемые сообщения об ошибках будут сохраняться в переменной
$php_errormsg.
Эта переменная будет перезаписываться при возникновении каждой новой ошибки,
поэтому в случае необходимости проверяйте ее сразу же.
Замечание:
Оператор @ работает только с
выражениями.
Есть простое правило: если произвольная языковая конструкция возвращает
значение, значит вы можете использовать предшествующий ей оператор
@. Например, вы можете использовать @ перед
именем переменной, произвольной функцией или вызовом include(),
константой и так далее. В то же время вы не можете использовать этот оператор
перед определением функции или класса, условными конструкциями, такими как if или
foreach.
Также ознакомьтесь с описанием функции error_reporting()
и соответствующим разделом документации
Обработка ошибок и функции логирования.
Замечание:
Оператор @ не подавляет вывод ошибок, возникающих на
стадии синтаксического разбора скрипта.
Внимание |
На сегодняшний день оператор @ подавляет
вывод сообщений даже о критических ошибках прерывающих работу
скрипта. Помимо всего прочего, это означает, что если вы использовали
@ для подавления ошибок, возникающих при работе какой-либо
функции, в случае если она недоступна или написана неправильно, дальнейшая
работа скрипта будет остановлена без каких-либо уведомлений.
|
Оператор управления ошибками
me at hesterc dot fsnet dot co dot uk
03-Mar-2005 08:25
If you wish to display some text when an error occurs, echo doesn't work. Use print instead. This is explained on the following link 'What is the difference between echo and print?':
http://www.faqts.com/knowledge_base/view.phtml/aid/1/fid/40
It says "print can be used as part of a more complex expression where echo cannot".
Also, you can add multiple code to the result when an error occurs by separating each line with "and". Here is an example:
<?php
$my_file = @file ('non_existent_file') or print 'File not found.' and $string = ' Honest!' and print $string and $fp = fopen ('error_log.txt', 'wb+') and fwrite($fp, $string) and fclose($fp);
?>
A shame you can't use curly brackets above to enclose multiple lines of code, like you can with an if statement or a loop. It could make for a single long line of code. You could always call a function instead.
frogger at netsurf dot de
26-Dec-2004 08:19
Better use the function trigger_error() (http://de.php.net/manual/en/function.trigger-error.php)
to display defined notices, warnings and errors than check the error level your self. this lets you write messages to logfiles if defined in the php.ini, output
messages in dependency to the error_reporting() level and suppress output using the @-sign.
webmaster __AT__ digitalanime __DOT__ nl
18-May-2004 03:10
Someone over here wanted to know how to use the @ in your error handler... It's easy:
<?php
function my_error_handler(.......)
{
if(error_reporting() == 0) {
}
else
{
}
}
?>
manicdepressive at mindless dot com
29-Feb-2004 04:44
taking the value of a non existant element:
$foo = @$array['not_here']
will work as described, setting $foo to NULL,
but taking a *reference* to a non-existant element:
$foo =& @$array['not_here']
will create the element with a NULL value, which $foo will then referece.
-- code till dawn, mark meves
sdavey at datalink dot net dot au
30-Nov-2003 04:26
To suppress error warnings for functions that use the error operator '@' in your own error handlers, I found a sentence on the set_error_handler() page that explains it:
manual/en/function.set-error-handler.php
To paraphrase, it says that PHP temporarily sets the value of error_reporting() to 0 when in the error handler.
So, if you have the following:
$fp = @fopen("non-existent-file", "r");
when your custom error handler function is called, you can check the value of error_reporting() like this:
function handler($type, $str, $file, $line, $info) {
// don't respond to the error if it
// was suppressed with a '@'
if (error_reporting() == 0) return;
// otherwise, handle the error
...
}
john-at-n0-spam-foobar-dot-nl
25-Jul-2003 10:04
With set_error_handler() you bypass the standard error handler, which takes care of @.
if (!($fp = @fopen('not_a_file', 'r')))
trigger_error("Can't open file!", E_USER_WARNING);
... generates ...
Warning: fopen("not_a_file", "r") - No such file or directory in index.php on line 19.
User Warning : Can't open file! in index.php on line 20.
... when I use my own error handler. With the standard error handler I only get the second warning.
If someone knows how to use @ with your own error handler, let me know.
psychohist at aol dot com
04-Jul-2003 01:59
if you create a new variable by assigning to it the error
suppressed value of an unset variable, the new variable
will be set, with a value of (I believe) null:
$new_variable // previously not set
= @$nonexistent_variable; // also not set
$next_variable = $new_variable // no warning generated
25-Apr-2003 06:24
It should be noted that suppressed error reporting is inherited, so to speak.
Consider this function:
function warning() {
$return = 10 / 0;
return $return;
}
This line will produce a warning;
var_dump(warning());
While these will not:
var_dump(@warning());
@var_dump(warning());
This might not be so obvious for some people; I know I didn't expect this behaviour.
19-Oct-2002 11:00
To suppress errors for a method inside a class, place the @ operator before the object and not before the method name.
// DO:
@$this->foo($bar);
// DON'T:
$this->@foo($bar);
drm at gerard dot yoursite dot nl
21-Aug-2002 03:50
When you check if an index of an array is set, you imply that the array itself already exists.
So
if ( isset ( $array [ 'index' ] ) ) {
}
would generate a notice if $array is not defined, but not if $array _is_ defined, but the index 'index' not.
And so on for nested arrays ofcourse
webmaster at speedy dot co dot il
06-Jul-2002 05:31
I don't know if this is a feature or bug, but this doesn't work:
if (!(isset(@$GLOBALS['SPEEDY_GLOBAL_VARS']['PAGE_NAME'])))
On the other hand, this works:
if (!(@isset($GLOBALS['SPEEDY_GLOBAL_VARS']['PAGE_NAME'])))
Regards,
Uri.
| |