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

search for in the

실행 연산자> <비교 연산자
Last updated: Sun, 25 Nov 2007

view this page in

에러 제어 연산자

PHP는 에러 제어 연산자를 지원한다: 앳 부호 (@). PHP에서 표현식의 앞에 덧붙이면, 그 표현식에서 발생할수 있는 에러 메시지가 출력되지 않도록 한다. track_errors 기능은 활성화되어있으면, 표현식에서 발생하는 모든 에러는 $php_errormsg변수에 저장될것이다. 이 변수는 에러가 발생할 때마다 덮어씌어질것이고, 그래서 이 변수를 사용하려면 바로바로 확인해야 한다.

<?php
/* Intentional file error */
$my_file = @file ('non_existent_file') or
    die (
"Failed opening file: error was '$php_errormsg'");

// this works for any expression, not just functions:
$value = @$cache[$key]; 
// will not issue a notice if the index $key doesn't exist.

?>

Note: @-연산자는 표현식에서만 동작한다. 단순한 규칙: 표현식의 값을 취할수 있으면, 그 표현식 앞에 @ 연산자를 덧붙일수 있다. 예를 들면, 변수, 함수, include()호출, 상수 등의 앞에 덧붙일수 있다. 그러나 함수나 클래스 선언부, if같은 조건문, foreach 등에 이 부호를 덧붙일수는 없다.

error_reporting()함수와 Error Handling and Logging functions에 관한 매뉴얼 섹션을 참고.

Note: "@" 에러-제어 연산자는 해석 에러로 인한 에러 메시지를 가릴수는 없을것이다.

Warning

현재 "@" 에러-제어 연산자는 스크립트 수행을 멈출수 있는 심각한 에러에 대한 에러 메시지들도 보이지 않게 할것이다. 이말의 의미는 어떤 함수에서 에러 메시지를 보이지 않게 하려하려고 "@"을 사용했고 그 함수가 가용하지 않거나 오타를 쓴것일지라도 이 스크립트는 에러 원인에 대한 메시지 없이 그자리에서 즉시 멈추게 될것이다.



실행 연산자> <비교 연산자
Last updated: Sun, 25 Nov 2007
 
add a note add a note User Contributed Notes
에러 제어 연산자
beatngu
27-May-2008 02:29
NB The @ operator doesn't work when throwing errors as exceptions using the ErrorException class
lewis [@t] hcoms [dot] co [dot] uk
02-Apr-2008 12:38
@John Chilton

"I happen to use it with variables all the time, and have also noticed the (IMHO) odd result when trying to stifle errors when asking isset() about a nonexistent variable. However, it does make more sense to use @isset($foo) than isset(@$foo) to me anyway..."

Using the @ symbol with isset() is useless. This is because isset() will not return an error if the variable is not existent (otherwise it would be pretty useless).
root at mantoru dot de
17-Oct-2007 12:13
The @ operator can also be prepended to literals (like strings), as they're also statements -- it will suppress any notice about uninitialized variables. If you want to silence a more complex expression (@ is unary), use braces.

<?php
// variable interpolation
$str = @"Then I said: '$maybeunset'.";

// integer stuffs
$result = @2 * 3 / 0; // = @(2) * 3 / 0 - WRONG (warning)
$result = @(2 * 3 / 0); // RIGHT (no warning), $result is false
?>

@John Chilton's post: As omelnyk said, isset is a language construct and NOT a function, and an @ token is not allowed there. @isset makes no sense, because under ANY circumstances isset stays quiet.
Also, "using it with variables all the time" is a VERY bad idea, because it will make your code EXTREMELY slow. Crank your error_reporting down then.
John Chilton
09-Jul-2007 03:18
To omelnyk:

It also says:

A simple rule of thumb is: if you can take the value of something, you can prepend the @ operator to it. For instance, you can prepend it to variables, function and include() calls....

"...you can prepend it to variables..."

I happen to use it with variables all the time, and have also noticed the (IMHO) odd result when trying to stifle errors when asking isset() about a nonexistent variable. However, it does make more sense to use @isset($foo) than isset(@$foo) to me anyway...
omelnyk at gmail dot com
18-May-2007 08:05
To webmaster at speedy dot co dot il:

it's not a bug. As the manual says, the @-operator works only on expressions, and isset() takes a variable, not expression, as its argument.
nospam at blog dot fileville dot net
03-Jan-2007 11: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...
12-Dec-2006 05: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 06: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 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) // error_reporting() = 0, so it was called with @ in front of it
 
{
   
// do nothing
 
}
  else
  {
  
// do something
 
}
}
?>
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:
http://www.php.net/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.

실행 연산자> <비교 연산자
Last updated: Sun, 25 Nov 2007
 
 
show source | credits | stats | sitemap | contact | advertising | mirror sites