W3docs

How to Use the @ Sign in PHP

The @ sign is one of the common used ones in programming. Let’s discover how it can be used in PHP together. Read on the snippet and check the examples.

In PHP, the @ sign is applied for controlling errors. In other words, it is an error suppression operator.

Here, we will check out two options of using this sign as an error suppression operator.

Warning

Before starting to use the @ sign as an error suppression operator, consider that it doesn’t make errors disappear. They just get hidden. Also, it might make debugging more difficult as you won’t be able to see what’s wrong with the code. Note that @ only suppresses runtime errors, not fatal errors.

Option 1

Once the @ sign is added before an expression, error messages that might be created by that expression are ignored.

In case the <kbd class="highlighted">track_errors</kbd> feature is activated, an error message will be created by that expression and saved inside the <kbd class="highlighted">$php_errormsg</kbd> variable.

That variable is overwritten every time.

Let’s see an example:

php, the @ sign in file error

<?php

// File error
($file = @file('non_existent_file')) or die("Failed in opening the file.");

// It is applied for expression
$value = @$cache['key'];

// Suppresses the notice if $cache is undefined.

?>

php failed to open the file

Failed in opening the file.

Option 2

Let’s see another usage example of the @ sign:

php using the @ sign

<?php

// Statement 1
$result = @$hello['123'];

// Statement 2
$result = $hello['123'];

?>

Only statement 1 will suppress the error. Statement 2 will trigger the notice, which will be displayed like this:

php notice message

PHP Notice: Undefined variable: hello.