PHP
downloads | documentation | faq | getting help | mailing lists | reporting bugs | php.net sites | links | conferences | my php.net

search for in the

Operadores de Execução> <Operadores de Comparação
Last updated: Fri, 22 Aug 2008

view this page in

Operadores de controle de erro

O PHP suporta um operador de controle de erro: o sinal 'arroba' (@). Quando ele precede uma expressão em PHP, qualquer mensagem de erro que possa ser gerada por aquela expressão será ignorada.

Se o recurso track_errors estiver habilitado, qualquer mensagem de erro gerada pela expressão será gravada na variável global $php_errormsg. Esta variável será sobrescrita em cada erro, assim verifique-a constantemente se você quiser usá-la.

<?php
/* Erro de arquivo intencional */
$my_file = @file ('arquivo_nao_existente') or
    die (
"Falha abrindo arquivo: '$php_errormsg'");

// Isto funciona para qualquer expressão, não apenas para funções:
$value = @$cache[$key];
// você não receberá nenhum aviso se a chave $key não existir.

?>

Nota: O operador @ funciona somente em expressões. Uma regra simples para lembrar disso: se você pode pegar o valor de alguma coisa, você pode prefixar isso com o @. Assim, você pode prefixar chamadas de variáveis, funções e include()s, constantes e afins. Você não pode prefixar definições de funções ou classe, estruturas condicionais como o if, foreach e assim por diante.

Veja também error_reporting() e a seção do manual sobre funções de Manipulação de Erros e Logging.

Nota: O prefixo de controle de erro "@" não desabilita mensagens que são resultado de erros de interpretação (parse errors).

Aviso

Atualmente, o operador de controle de erro "@" sempre desativa mensagens de erro, mesmo para erros críticos, que terminam a execução de scripts. Além de outras coisas, isto significa que se você usar "@" para suprimir erros de certas funções e elas não estiverem disponíveis ou com tipos incorretos, o script vai parar exatamente aí sem nenhuma indicação da razão.



Operadores de Execução> <Operadores de Comparação
Last updated: Fri, 22 Aug 2008
 
add a note add a note User Contributed Notes
Operadores de controle de erro
taras dot dot dot di at gmail dot com
12-Aug-2008 05:29
I was confused as to what the @ symbol actually does, and after a few experiments have concluded the following:

* the error handler that is set gets called regardless of what level the error reporting is set on, or whether the statement is preceeded with @

* it is up to the error handler to impart some meaning on the different error levels. You could make your custom error handler echo all errors, even if error reporting is set to NONE.

* so what does the @ operator do? It temporarily sets the error reporting level to 0 for that line. If that line triggers an error, the error handler will still be called, but it will be called with an error level of 0

Hope this helps someone
beatngu
27-May-2008 11:29
NB The @ operator doesn't work when throwing errors as exceptions using the ErrorException class
nospam at blog dot fileville dot net
03-Jan-2007 08:58
If you want to log all the error messages for a php script from a session you can use something like this:
<?php
 session_start
();
  function
error($error, $return=FALSE) {
      global
$php_errormsg;
      if(isset(
$_SESSION['php_errors'])) {
       
$_SESSION['php_errors'] = array();    
    }
 
$_SESSION['php_errors'][] = $error; // Maybe use $php_errormsg
 
if($return == TRUE) {
   
$message = "";
       foreach(
$_SESSION['php_errors'] as $php_error) {
         
$messages .= $php_error."\n";
     } 
    return
$messages; // Or you can use use $_SESSION['php_errors']
 
}
}
?>
Hope this helps someone...
13-Dec-2006 02:52
error_reporting()==0 for detecting the @ error suppression assumes that you did not set the error level to 0 in the first place.

However, typically if you want to set your own error handler, you would set the error_reporting to 0. Therefore, an alternative to detect the @ error suppression is required.
programming at kennebel dot com
13-Oct-2006 03:38
To suppress errors for a new class/object:

<?php
// Tested: PHP 5.1.2 ~ 2006-10-13

// Typical Example
$var = @some_function();

// Class/Object Example
$var = @new some_class();

// Does NOT Work!
//$var = new @some_class(); // syntax error
?>

I found this most useful when connecting to a
database, where i wanted to control the errors
and warnings displayed to the client, while still
using the class style of access.
me at hesterc dot fsnet dot co dot uk
03-Mar-2005 05: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 05: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.

Operadores de Execução> <Operadores de Comparação
Last updated: Fri, 22 Aug 2008
 
 
show source | credits | sitemap | contact | advertising | mirror sites