Programing

PHP에서 @ 기호를 사용하는 것은 무엇입니까?

lottogame 2020. 10. 4. 10:15
반응형

PHP에서 @ 기호를 사용하는 것은 무엇입니까?


@다음과 같은 특정 기능 앞에의 사용을 보았습니다 .

$fileHandle = @fopen($fileName, $writeAttributes);

이 기호의 용도는 무엇입니까?


오류 메시지를 억제합니다 . PHP 매뉴얼의 오류 제어 연산자참조하십시오 .


오류를 억제합니다.

설명서에서 오류 제어 연산자참조하십시오 .

PHP는 하나의 오류 제어 연산자 인 at 기호 (@)를 지원합니다. PHP에서 표현식 앞에 추가되면 해당 표현식에 의해 생성 될 수있는 오류 메시지가 무시됩니다.

set_error_handler ()사용하여 사용자 지정 오류 처리기 함수를 설정 한 경우 에도 여전히 호출되지만이 사용자 지정 오류 처리기는 error_reporting () 을 호출 할 수 있으며 오류를 트리거 한 호출 앞에 @가 올 때 0을 반환합니다. ...


@심볼은 인 오류 제어 연산자 (일명 "침묵"또는 "차단해서"연산자). PHP는 관련 표현식에 의해 생성 된 오류 메시지 (알림, 경고, 치명적 등)를 억제합니다. 예를 들어 단항 연산자처럼 작동하며 우선 순위와 연관성이 있습니다. 다음은 몇 가지 예입니다.

@echo 1 / 0;
// generates "Parse error: syntax error, unexpected T_ECHO" since 
// echo is not an expression

echo @(1 / 0);
// suppressed "Warning: Division by zero"

@$i / 0;
// suppressed "Notice: Undefined variable: i"
// displayed "Warning: Division by zero"

@($i / 0);
// suppressed "Notice: Undefined variable: i"
// suppressed "Warning: Division by zero"

$c = @$_POST["a"] + @$_POST["b"];
// suppressed "Notice: Undefined index: a"
// suppressed "Notice: Undefined index: b"

$c = @foobar();
echo "Script was not terminated";
// suppressed "Fatal error: Call to undefined function foobar()"
// however, PHP did not "ignore" the error and terminated the
// script because the error was "fatal"

표준 PHP 오류 처리기 대신 사용자 지정 오류 처리기를 사용하면 정확히 어떻게 되나요?

set_error_handler ()를 사용하여 사용자 지정 오류 처리기 함수를 설정 한 경우에도 여전히 호출되지만이 사용자 지정 오류 처리기는 error_reporting ()을 호출 할 수 있으며 오류를 트리거 한 호출 앞에 @가 올 때 0을 반환합니다. .

이는 다음 코드 예제에 설명되어 있습니다.

function bad_error_handler($errno, $errstr, $errfile, $errline, $errcontext) {
    echo "[bad_error_handler]: $errstr";
    return true;
}
set_error_handler("bad_error_handler");
echo @(1 / 0);
// prints "[bad_error_handler]: Division by zero"

The error handler did not check if @ symbol was in effect. The manual suggests the following:

function better_error_handler($errno, $errstr, $errfile, $errline, $errcontext) {
    if(error_reporting() !== 0) {
        echo "[better_error_handler]: $errstr";
    }
    // take appropriate action
    return true;
}

Also note that despite errors being hidden, any custom error handler (set with set_error_handler) will still be executed!


Like already some answered before: The @ operator suppresses all errors in PHP, including notices, warnings and even critical errors.

BUT: Please, really do not use the @ operator at all.

Why?

Well, because when you use the @ operator for error supression, you have no clue at all where to start when an error occurs. I already had some "fun" with legacy code where some developers used the @ operator quite often. Especially in cases like file operations, network calls, etc. Those are all cases where lots of developers recommend the usage of the @ operator as this sometimes is out of scope when an error occurs here (for example a 3rdparty API could be unreachable, etc.).

But what's the point to still not use it? Let's have a look from two perspectives:

As a developer: When @ is used, I have absolutely no idea where to start. If there are hundreds or even thousands of function calls with @ the error could be like everyhwere. No reasonable debugging possible in this case. And even if it is just a 3rdparty error - then it's just fine and you're done fast. ;-) Moreover, it's better to add enough details to the error log, so developers are able to decide easily if a log entry is something that must be checked further or if it's just a 3rdparty failure that is out of the developer's scope.

As a user: Users don't care at all what the reason for an error is or not. Software is there for them to work, to finish a specific task, etc. They don't care if it's the developer's fault or a 3rdparty problem. Especially for the users, I strongly recommend to log all errors, even if they're out of scope. Maybe you'll notice that a specific API is offline frequently. What can you do? You can talk to your API partner and if they're not able to keep it stable, you should probably look for another partner.

In short: You should know that there exists something like @ (knowledge is always good), but just do not use it. Many developers (especially those debugging code from others) will be very thankful.


Suppose we haven't used the "@" operator then our code would look like this:

$fileHandle = fopen($fileName, $writeAttributes);

And what if the file we are trying to open is not found? It will show an error message.

To suppress the error message we are using the "@" operator like:

$fileHandle = @fopen($fileName, $writeAttributes);

If the open fails, an error of level E_WARNING is generated. You may use @ to suppress this warning.


@ suppresses error messages.

It is used in code snippets like:

@file_get_contents('http://www.exaple.com');

If domain "http://www.exaple.com" is not accessible, an error will be shown, but with @ nothing is not showed.


PHP supports one error control operator: the at sign (@). When prepended to an expression in PHP, any error messages that might be generated by that expression will be ignored.

If you have set a custom error handler function with set_error_handler() then it will still get called, but this custom error handler can (and should) call error_reporting() which will return 0 when the call that triggered the error was preceded by an @.

<?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:-

1) The @-operator works only on expressions.

2) 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, constants, and so forth. You cannot prepend it to function or class definitions, or conditional structures such as if and foreach, and so forth.

Warning:-

Currently the "@" error-control operator prefix will even disable error reporting for critical errors that will terminate script execution. Among other things, this means that if you use "@" to suppress errors from a certain function and either it isn't available or has been mistyped, the script will die right there with no indication as to why.


It might be worth adding here there are a few pointers when using the @ you should be aware of, for a complete run down view this post: http://mstd.eu/index.php/2016/06/30/php-rapid-fire-what-is-the-symbol-used-for-in-php/

  1. The error handler is still fired even with the @ symbol prepended, it just means a error level of 0 is set, this will have to be handled appropriately in a custom error handler.

  2. Prepending a include with @ will set all errors in the include file to an error level of 0


@ suppresses the error message thrown by the function. fopen throws an error when the file doesn't exit. @ symbol makes the execution to move to the next line even the file doesn't exists. My suggestion would be not using this in your local environment when you develop a PHP code.

참고URL : https://stackoverflow.com/questions/1032161/what-is-the-use-of-the-symbol-in-php

반응형