IT TIP

PHP의 엄격한 모드?

itqueen 2020. 11. 30. 20:33
반응형

PHP의 엄격한 모드?


자동 변수 선언을 사용하는 다른 언어 (예 : Perl)에는 엄격 모드가 있습니다.

이 엄격 모드를 활성화하면 변수 선언이 필요하며 선언되지 않은 변수를 사용하려고하면 Perl에서 오류가 발생합니다.

PHP가 유사한 기능을 제공합니까?


거의. 오류보고E_NOTICE 에서 수준을 활성화 할 수 있습니다 . (상수 목록은 여기에 있습니다 .)

선언되지 않은 변수를 사용하는 모든 인스턴스는 E_NOTICE.

E_STRICT오류 수준은 코드를 최적화하는 방법에 그 사항뿐만 아니라 다른 힌트를 던질 것이다.

error_reporting(E_STRICT);

스크립트 종료

정말로 진지 하고 선언되지 않은 변수가 발생할 때 알림을 출력하는 대신 스크립트를 종료 하려면 사용자 지정 오류 처리기를 만들 수 있습니다.

E_NOTICE"Undefined variable"이있는 s 만 처리 하고 나머지 모든 것을 기본 PHP 오류 처리기에 전달 하는 작업 예제 :

<?php

error_reporting(E_STRICT);

function terminate_missing_variables($errno, $errstr, $errfile, $errline)
{                               
  if (($errno == E_NOTICE) and (strstr($errstr, "Undefined variable")))
   die ("$errstr in $errfile line $errline");

  return false; // Let the PHP error handler handle all the rest  
}

$old_error_handler = set_error_handler("terminate_missing_variables"); 

echo $test; // Will throw custom error

xxxx();  // Will throw standard PHP error

 ?>

사용하다

error_reporting(-1);

E_STRICT새로운 수준과 상수가 향후 PHP 버전에 추가되는 경우를 포함하여 가능한 모든 오류를 표시합니다 .

( 참조 )


몇 년 후, PHP 7.0.0은 declare(strict_types=1);

http://php.net/manual/en/functions.arguments.php#functions.arguments.type-declaration.strict


예, error_reporting(E_STRICT|E_ALL);스크립트 시작 부분을 입력하십시오.


을 확인 error_reporting하고 설정하는 것을 잊지 마십시오 display_errors. 여러 수준의 오류보고가 있습니다.


사용하다

error_reporting(E_ALL);

PHP 코드 시작 부분에. 또는 php.ini 파일에서 error_reporting 설정을 설정하여 모든 PHP 파일에 대해 설정하십시오.


PHP 기본적으로 선언되지 않은 변수에 대해 경고 합니다. 알림을 볼 수 있도록 오류보고 수준을 높이기 만하면 됩니다. PHP에서 변수를 선언하는 특별한 구문이없고 할당하여 선언하기 만하면 선언 되지 않은 변수 의 값사용 하려고 할 때만 경고 할 수 있습니다 . 다른 언어와 달리 "선언되지 않은 변수에 대한 할당"은 존재하지 않으므로 PHP가 경고 할 수 없습니다.


를 사용하여 고유 한 오류 처리 기능을 구현할 수 있습니다 set_error_handler().

그런 다음 원하는대로 특정 오류 수준에 대응할 수 있습니다.

예를 들어, 오류 메시지를 표시하고 로깅하는 대신 변수가 제대로 선언되지 않았거나 원하지 않는 조건이 충족되면 스크립트를 종료 할 수 있습니다.

이렇게하면 PHP 인터프리터 인스턴스에서 실행되는 모든 코드에 대해 매우 엄격한 정책을 시행 할 수 있습니다.


예, 오류보고를 사용합니다.

http://www.php.net/manual/en/function.error-reporting.php


오류보고 및 처리에 대한 요구 사항은 개발 환경과 라이브 프로덕션 환경 (WWW, 회사 인트라넷 등) 내에서 다릅니다. 개발 중에 문제를 찾아 수정하기 위해 가능한 한 많은 세부 정보를보고 싶을 것입니다.

In the live environment, I think don't that you want to show PHP error messages to the users but rather allow the script to continue with reduced functionality (eg. a message like "Sorry we cannot update your profile at the moment", or redirect the user to the home page, etc). A way to achieve this would be through the use to custom error handlers for each environment


A 2019 response to this old question,

Yes you can from PHP 7.X onwards,

declare(strict_types=1);

This will enforce all the scalar type declarations to be strict with types.

But if you enable this globally it can affect other 3rd party modules (Eg - Composer libraries) which are relying in weak mode, so make sure to enforce it in relevant classes/files.

참고URL : https://stackoverflow.com/questions/3193072/strict-mode-in-php

반응형