Error types php

Перечисленные ниже константы всегда доступны как часть ядра PHP.

Предопределённые константы

Перечисленные ниже константы всегда доступны как часть ядра PHP.

Замечание:

Данные имена констант можно использовать в файле php.ini но не вне PHP,
как например в файле httpd.conf, где вместо них необходимо использовать значения их
битовых масок.

Ошибки и протоколирование

Значение Константа Описание Примечание
1 E_ERROR
(int)
Фатальные ошибки времени выполнения. Это неустранимые средствами самого
скрипта ошибки, такие как ошибка распределения памяти и т.п.
Выполнение скрипта в таком случае прекращается.
 
2 E_WARNING
(int)
Предупреждения времени выполнения (не фатальные ошибки).
Выполнение скрипта в таком случае не прекращается.
 
4 E_PARSE
(int)
Ошибки на этапе компиляции. Должны генерироваться
только парсером.
 
8 E_NOTICE
(int)
Уведомления времени выполнения. Указывают на то, что во время выполнения скрипта
произошло что-то, что может указывать на ошибку, хотя это может происходить
и при обычном выполнении программы.
 
16 E_CORE_ERROR
(int)
Фатальные ошибки, которые происходят во время запуска РНР. Такие ошибки схожи с
E_ERROR, за исключением того, что они генерируются ядром PHP.
 
32 E_CORE_WARNING
(int)
Предупреждения (не фатальные ошибки), которые происходят во время начального запуска РНР.
Такие предупреждения схожи с E_WARNING, за исключением того,
что они генерируются ядром PHP.
 
64 E_COMPILE_ERROR
(int)
Фатальные ошибки на этапе компиляции. Такие ошибки
схожи с E_ERROR, за исключением того,
что они генерируются скриптовым движком Zend.
 
128 E_COMPILE_WARNING
(int)
Предупреждения на этапе компиляции (не фатальные ошибки). Такие
предупреждения схожи с E_WARNING, за
исключением того, что они генерируются скриптовым движком Zend.
 
256 E_USER_ERROR
(int)
Сообщения об ошибках, сгенерированные пользователем. Такие
ошибки схожи с E_ERROR, за исключением
того, что они генерируются в коде скрипта средствами функции
PHP trigger_error().
 
512 E_USER_WARNING
(int)
Предупреждения, сгенерированные пользователем. Такие
предупреждения схожи с E_WARNING,
за исключением того, что они генерируются в коде скрипта
средствами функции PHP trigger_error().
 
1024 E_USER_NOTICE
(int)
Уведомления, сгенерированные пользователем. Такие уведомления
схожи с E_NOTICE, за исключением того,
что они генерируются в коде скрипта, средствами
функции PHP trigger_error().
 
2048 E_STRICT
(int)
Включаются для того, чтобы PHP предлагал изменения в коде, которые
обеспечат лучшее взаимодействие и совместимость кода.
 
4096 E_RECOVERABLE_ERROR
(int)
Фатальные ошибки с возможностью обработки. Такие ошибки указывают, что,
вероятно, возникла опасная ситуация, но при этом, скриптовый движок остаётся в стабильном состоянии.
Если такая ошибка не обрабатывается функцией, определённой пользователем для обработки ошибок
(смотрите set_error_handler()), выполнение приложения прерывается, как происходит
при ошибках E_ERROR.
 
8192 E_DEPRECATED
(int)
Уведомления времени выполнения об использовании устаревших
конструкций. Включаются для того, чтобы получать предупреждения
о коде, который не будет работать в следующих версиях PHP.
 
16384 E_USER_DEPRECATED
(int)
Уведомления времени выполнения об использовании устаревших
конструкций, сгенерированные пользователем. Такие уведомления
схожи с E_DEPRECATED за исключением того,
что они генерируются в коде скрипта, с помощью функции PHP
trigger_error().
 
32767 E_ALL
(int)
Все поддерживаемые ошибки, предупреждения и замечания.  

Представленные выше значения (как числовые, так и символьные)
используются для задания битовой маски, определяющей об ошибках
какого типа будет даваться отчёт. Вы можете использовать
побитовые операторы,
чтобы совмещать эти значения для указания определённых типов ошибок.
Стоит отметить, что в php.ini допустимы только следующие
операторы: ‘|’, ‘~’, ‘!’, ‘^’ и ‘&’.

russthom at fivegulf dot com

10 years ago


[Editor's note: fixed E_COMPILE_* cases that incorrectly returned E_CORE_* strings. Thanks josiebgoode.]

The following code expands on Vlad's code to show all the flags that are set.  if not set, a blank line shows.

<?php

$errLvl
= error_reporting();

for (
$i = 0; $i < 15$i++ ) {

    print
FriendlyErrorType($errLvl & pow(2, $i)) . "<br>\n";

}

function

FriendlyErrorType($type)

{

    switch(
$type)

    {

        case
E_ERROR: // 1 //

           
return 'E_ERROR';

        case
E_WARNING: // 2 //

           
return 'E_WARNING';

        case
E_PARSE: // 4 //

           
return 'E_PARSE';

        case
E_NOTICE: // 8 //

           
return 'E_NOTICE';

        case
E_CORE_ERROR: // 16 //

           
return 'E_CORE_ERROR';

        case
E_CORE_WARNING: // 32 //

           
return 'E_CORE_WARNING';

        case
E_COMPILE_ERROR: // 64 //

           
return 'E_COMPILE_ERROR';

        case
E_COMPILE_WARNING: // 128 //

           
return 'E_COMPILE_WARNING';

        case
E_USER_ERROR: // 256 //

           
return 'E_USER_ERROR';

        case
E_USER_WARNING: // 512 //

           
return 'E_USER_WARNING';

        case
E_USER_NOTICE: // 1024 //

           
return 'E_USER_NOTICE';

        case
E_STRICT: // 2048 //

           
return 'E_STRICT';

        case
E_RECOVERABLE_ERROR: // 4096 //

           
return 'E_RECOVERABLE_ERROR';

        case
E_DEPRECATED: // 8192 //

           
return 'E_DEPRECATED';

        case
E_USER_DEPRECATED: // 16384 //

           
return 'E_USER_DEPRECATED';

    }

    return
"";

}

?>


Andy at Azurite (co uk)

11 years ago


-1 is also semantically meaningless as a bit field, and only works in 2s-complement numeric representations.  On a 1s-complement system -1 would not set E_ERROR.  On a sign-magnitude system -1 would set nothing at all! (see e.g. http://en.wikipedia.org/wiki/Ones%27_complement)

If you want to set all bits, ~0 is the correct way to do it.

But setting undefined bits could result in undefined behaviour and that means *absolutely anything* could happen :-)


fadhilinjagi at gmail dot com

1 year ago


A simple and neat way to get the error level from the error code. You can even customize the error level names further.

<?php
$exceptions
= [
       
E_ERROR => "E_ERROR",
       
E_WARNING => "E_WARNING",
       
E_PARSE => "E_PARSE",
       
E_NOTICE => "E_NOTICE",
       
E_CORE_ERROR => "E_CORE_ERROR",
       
E_CORE_WARNING => "E_CORE_WARNING",
       
E_COMPILE_ERROR => "E_COMPILE_ERROR",
       
E_COMPILE_WARNING => "E_COMPILE_WARNING",
       
E_USER_ERROR => "E_USER_ERROR",
       
E_USER_WARNING => "E_USER_WARNING",
       
E_USER_NOTICE => "E_USER_NOTICE",
       
E_STRICT => "E_STRICT",
       
E_RECOVERABLE_ERROR => "E_RECOVERABLE_ERROR",
       
E_DEPRECATED => "E_DEPRECATED",
       
E_USER_DEPRECATED => "E_USER_DEPRECATED",
       
E_ALL => "E_ALL"
];

echo

$exceptions["1"];
$code = 256;
echo
$exceptions[$code];
?>

Output: 
E_ERROR
E_USER_ERROR

This will need updating when PHP updates the error level names. Otherwise, it works just fine.


cl at viazenetti dot de

5 years ago


An other way to get all PHP errors  that are set to be reported. This code will even work, when additional error types are added in future.

<?php
$pot
= 0;
foreach (
array_reverse(str_split(decbin(error_reporting()))) as $bit) {
    if (
$bit == 1) {
        echo
array_search(pow(2, $pot), get_defined_constants(true)['Core']). "<br>n";
    }
   
$pot++;
}
?>


bbrokman at gmail dot com

3 years ago


A neat way to have a place in code to control error reporting configuration :)

<?php

$errorsActive

= [
   
E_ERROR             => FALSE,
   
E_WARNING           => TRUE,
   
E_PARSE             => TRUE,
   
E_NOTICE            => TRUE,
   
E_CORE_ERROR        => FALSE,
   
E_CORE_WARNING      => FALSE,
   
E_COMPILE_ERROR     => FALSE,
   
E_COMPILE_WARNING   => FALSE,
   
E_USER_ERROR        => TRUE,
   
E_USER_WARNING      => TRUE,
   
E_USER_NOTICE       => TRUE,
   
E_STRICT            => FALSE,
   
E_RECOVERABLE_ERROR => TRUE,
   
E_DEPRECATED        => FALSE,
   
E_USER_DEPRECATED   => TRUE,
   
E_ALL               => FALSE,
];
error_reporting(
   
array_sum(
       
array_keys($errorsActive, $search = true)
    )
);
?>


kaioker

1 year ago


super simple error code to human readable conversion:

function prettycode($code){
    return $code == 0 ? "FATAL" : array_search($code, get_defined_constants(true)['Core']);
}


ahsankhatri1992 at gmail

6 years ago


Notes posted above limited to current errors level as on 26th Aug 2016, following snippet will work even on introduction of new error level

$errLvl = error_reporting();
for ( $i = 1; $i < E_ALL;  $i*=2 )
{
    print FriendlyErrorType($errLvl & $i) . "<br>n";
}

function FriendlyErrorType($type)
{
    switch($type)
    {
        case E_ERROR: // 1 //
            return 'E_ERROR';
        case E_WARNING: // 2 //
            return 'E_WARNING';
        case E_PARSE: // 4 //
            return 'E_PARSE';
        case E_NOTICE: // 8 //
            return 'E_NOTICE';
        case E_CORE_ERROR: // 16 //
            return 'E_CORE_ERROR';
        case E_CORE_WARNING: // 32 //
            return 'E_CORE_WARNING';
        case E_COMPILE_ERROR: // 64 //
            return 'E_COMPILE_ERROR';
        case E_COMPILE_WARNING: // 128 //
            return 'E_COMPILE_WARNING';
        case E_USER_ERROR: // 256 //
            return 'E_USER_ERROR';
        case E_USER_WARNING: // 512 //
            return 'E_USER_WARNING';
        case E_USER_NOTICE: // 1024 //
            return 'E_USER_NOTICE';
        case E_STRICT: // 2048 //
            return 'E_STRICT';
        case E_RECOVERABLE_ERROR: // 4096 //
            return 'E_RECOVERABLE_ERROR';
        case E_DEPRECATED: // 8192 //
            return 'E_DEPRECATED';
        case E_USER_DEPRECATED: // 16384 //
            return 'E_USER_DEPRECATED';
    }
    return "";
}


kezzyhko at NOSPAM dot semysha dot ru

6 years ago


As for me, the best way to get error name by int value is that. And it's works fine for me ;)
<?php

array_flip

(array_slice(get_defined_constants(true)['Core'], 1, 15, true))[$type];//the same in readable form
array_flip(
   
array_slice(
       
get_defined_constants(true)['Core'],
       
1,
       
15,
       
true
   
)
)[
$type]?>

ErikBachmann

3 years ago


A shorter version of vladvarna's FriendlyErrorType($type)
<?php
function getErrorTypeByValue($type) {
   
$constants  = get_defined_constants(true);

    foreach (

$constants['Core'] as $key => $value ) { // Each Core constant
       
if ( preg_match('/^E_/', $key  ) ) {    // Check error constants
           
if ( $type == $value )
                return(
"$key=$value");
        }
    }
}  
// getErrorTypeByValue() echo "[".getErrorTypeByValue( 1 ) . "]". PHP_EOL;
echo
"[".getErrorTypeByValue( 0 ) . "]". PHP_EOL;
echo
"[".getErrorTypeByValue( 8 ) . "]". PHP_EOL;
?>

Will give
    [E_ERROR=1]
    []
    [E_NOTICE=8]

Anonymous

6 years ago


My version!
For long list function returns for example "E_ALL without E_DEPRECATED "

function errorLevel()
{
    $levels = array(
        'E_ERROR',
        'E_WARNING',
        'E_PARSE',
        'E_NOTICE',
        'E_CORE_ERROR',
        'E_CORE_WARNING',
        'E_COMPILE_ERROR',
        'E_COMPILE_WARNING',
        'E_USER_ERROR',
        'E_USER_WARNING',
        'E_USER_NOTICE',
        'E_STRICT',
        'E_RECOVERABLE_ERROR',
        'E_DEPRECATED',
        'E_USER_DEPRECATED',
        'E_ALL'
    );
    $excluded = $included = array();
    $errLvl = error_reporting();
    foreach ($levels as $lvl) {
        $val = constant($lvl);
        if ($errLvl & $val) {
            $included []= $lvl;
        } else {
                $excluded []= $lvl;
        }
    }
    if (count($excluded) > count($included)) {
        echo '<br />Consist: '.implode(',', $included);
    } else {
        echo '<br />Consist: E_ALL without '.implode(',', $excluded);
    }
}


vladvarna at gmail dot com

10 years ago


function FriendlyErrorType($type)
    {
        switch($type)
            {
            case E_ERROR: // 1 //
                return 'E_ERROR';
            case E_WARNING: // 2 //
                return 'E_WARNING';
            case E_PARSE: // 4 //
                return 'E_PARSE';
            case E_NOTICE: // 8 //
                return 'E_NOTICE';
            case E_CORE_ERROR: // 16 //
                return 'E_CORE_ERROR';
            case E_CORE_WARNING: // 32 //
                return 'E_CORE_WARNING';
            case E_CORE_ERROR: // 64 //
                return 'E_COMPILE_ERROR';
            case E_CORE_WARNING: // 128 //
                return 'E_COMPILE_WARNING';
            case E_USER_ERROR: // 256 //
                return 'E_USER_ERROR';
            case E_USER_WARNING: // 512 //
                return 'E_USER_WARNING';
            case E_USER_NOTICE: // 1024 //
                return 'E_USER_NOTICE';
            case E_STRICT: // 2048 //
                return 'E_STRICT';
            case E_RECOVERABLE_ERROR: // 4096 //
                return 'E_RECOVERABLE_ERROR';
            case E_DEPRECATED: // 8192 //
                return 'E_DEPRECATED';
            case E_USER_DEPRECATED: // 16384 //
                return 'E_USER_DEPRECATED';
            }
        return $type;
    }

PhpMyCoder

12 years ago


Well, technically -1 will show all errors which includes any new ones included by PHP. My guess is that E_ALL will always include new error constants so I usually prefer:

<?php

error_reporting
(E_ALL | E_STRICT);

?>



Reason being: With a quick glance anyone can tell you what errors are reported. -1 might be a bit more cryptic to newer programmers.


Anonymous

10 years ago


this would give you all the reported exception list of your configuration.

<?php

function FriendlyErrorType($type)

{

   
$return ="";

    if(
$type & E_ERROR) // 1 //

       
$return.='& E_ERROR ';

    if(
$type & E_WARNING) // 2 //

       
$return.='& E_WARNING ';

    if(
$type & E_PARSE) // 4 //

       
$return.='& E_PARSE ';

    if(
$type & E_NOTICE) // 8 //

       
$return.='& E_NOTICE ';

    if(
$type & E_CORE_ERROR) // 16 //

       
$return.='& E_CORE_ERROR ';

    if(
$type & E_CORE_WARNING) // 32 //

       
$return.='& E_CORE_WARNING ';

    if(
$type & E_COMPILE_ERROR) // 64 //

       
$return.='& E_COMPILE_ERROR ';

    if(
$type & E_COMPILE_WARNING) // 128 //

       
$return.='& E_COMPILE_WARNING ';

    if(
$type & E_USER_ERROR) // 256 //

       
$return.='& E_USER_ERROR ';

    if(
$type & E_USER_WARNING) // 512 //

       
$return.='& E_USER_WARNING ';

    if(
$type & E_USER_NOTICE) // 1024 //

       
$return.='& E_USER_NOTICE ';

    if(
$type & E_STRICT) // 2048 //

       
$return.='& E_STRICT ';

    if(
$type & E_RECOVERABLE_ERROR) // 4096 //

       
$return.='& E_RECOVERABLE_ERROR ';

    if(
$type & E_DEPRECATED) // 8192 //

       
$return.='& E_DEPRECATED ';

    if(
$type & E_USER_DEPRECATED) // 16384 //

       
$return.='& E_USER_DEPRECATED ';

    return
substr($return,2);

}

echo
"error_reporting = " . FriendlyErrorType(ini_get('error_reporting')) .";<br>";

?>


Herbert

6 years ago


if you want to bring this list back to the categories error/warning/notice/all

<?php

$error_level  

= 'warning';      //  Allowed values: error/warning/notice/all$error_error   = (int)                  E_ERROR | E_USER_ERROR | E_CORE_ERROR | E_COMPILE_ERROR | E_RECOVERABLE_ERROR | E_PARSE;
$error_warning = (int) $error_error   | E_WARNING | E_USER_WARNING | E_CORE_WARNING | E_COMPILE_WARNING;
$error_notice  = (int) $error_warning | E_NOTICE | E_USER_NOTICE | E_DEPRECATED | E_USER_DEPRECATED;
$error_all     = (int) $error_notice  | E_STRICT;error_reporting ($GLOBALS["error_$error_level"]);?>


espertalhao04 at hotmail dot com

5 years ago


A simplified way of writting a function to return a (non-optimal) representation of the error code as a bitwise string:

<?php
   
function readable_error_type($error_code)
    {
       
$constants = array();
        foreach(
get_defined_constants() as $key => $value)
        {
            if(
strpos($key, 'E_') === 0 && ($value <= $error_code) && ($value & $error_code))
            {
               
$constants[] = $key;
            }
        }

        return

implode(' | ', $constants);
    }
?>

This only works for values above 0.


ilpaijin at gmail dot com

5 years ago


The bitmask values relative to the Constant E_ALL is 30719, in case of PHP 5.6.x

damian at thebestisp dot dot dot com

6 years ago


I saw that Chris seems to think that errors might be combined in some cases, I don't know of any cases, but his code is overly verbose, inefficient, and doesn't take into account future E_ constants. Here's my version of handling multiple errors (which probably wont ever happen) using my other code as a base. The only real difference is that this doesn't bother to split out undefined bits, which is pretty much useless and would get rather messy if you have more than a few bits set above 2**14 (0 to 14 have an associated error).

<?php
function friendly_error_type($type) {
    static
$levels=null;
    if (
$levels===null) {
       
$levels=[];
        foreach (
get_defined_constants() as $key=>$value) {
            if (
strpos($key,'E_')!==0) {continue;}
           
$levels[$value]=substr($key,2);
        }
    }
   
$out=[];
    foreach (
$levels as $int=>$string) {
        if (
$int&$type) {$out[]=$string;}
       
$type&=~$int;
    }
    if (
$type) {$out[]="Error Remainder [{$type}]";}
    return
implode(' & ',$out);
}
echo
friendly_error_type(E_ERROR|E_USER_DEPRECATED); //ERROR & USER_DEPRECATED
echo friendly_error_type(2**20-1); //ERROR & RECOVERABLE_ERROR & WARNING & PARSE & NOTICE & STRICT & DEPRECATED & CORE_ERROR & CORE_WARNING & COMPILE_ERROR & COMPILE_WARNING & USER_ERROR & USER_WARNING & USER_NOTICE & USER_DEPRECATED & Error Remainder [1015808]
?>


damian at thebestisp dot dot dot com

6 years ago


I use this code to help mimic the default error handler, the only difference is that the levels end up being all caps, which I don't care to fix. You could also get rid of the underscores, but again, I don't care :P
Until php starts adding constants starting with E_ that have values overlapping with other E_ constants, this seems to be the shortest way of converting error code integers to strings understandable by meat bags. It will also work with new types, so that's nice.
<?php
function friendly_error_type($type) {
    static
$levels=null;
    if (
$levels===null) {
       
$levels=[];
        foreach (
get_defined_constants() as $key=>$value) {
            if (
strpos($key,'E_')!==0) {continue;}
           
$levels[$value]=substr($key,2);
        }
    }
    return (isset(
$levels[$type]) ? $levels[$type] : "Error #{$type}");
}
echo
friendly_error_type(1); #ERROR
echo friendly_error_type(2); #WARNING
echo friendly_error_type(3); #Error #3
?>
Tested on 5.6.12 and 7.0.3 (The first was by accident, didn't realize I was sshed into production :3)

chris-php at IGNORETHISPART dot cybermato dot com

8 years ago


How about this?  Unlike the examples below, it will show all the bits that are set, AND handle any bits defined in the future (at least not silently hide them)...

    $strErrorType = "";
    $bit = 1;
    $tmpErrNo = $errNo;
    while ($tmpErrNo) {
        if ($tmpErrNo & $bit) {
            if ($strErrorType != "")
                $strErrorType .= " | ";
            switch ($bit) {
            case E_USER_WARNING:
                $strErrorType .= "E_USER_WARNING"; break;
            case E_USER_NOTICE:
                $strErrorType .= "E_USER_NOTICE"; break;
            case E_WARNING:
                $strErrorType .= "E_WARNING"; break;
            case E_CORE_WARNING:
                $strErrorType .= "E_CORE_WARNING"; break;
            case E_COMPILE_WARNING:
                $strErrorType .= "E_COMPILE_WARNING"; break;
            case E_NOTICE:
                $strErrorType .= "E_NOTICE"; break;
            case E_ERROR:
                $strErrorType .= "E_ERROR"; break;
            case E_PARSE:
                $strErrorType .= "E_PARSE"; break;
            case E_CORE_ERROR:
                $strErrorType .= "E_CORE_ERROR"; break;
            case E_COMPILE_ERROR:
                $strErrorType .= "E_COMPILE_ERROR"; break;
            case E_USER_ERROR:
                $strErrorType .= "E_USER_ERROR"; break;  
            default:
                $strErrorType .= "(unknown error bit $bit)"; break;
            }
        }
        $tmpErrNo &= ~$bit;
        $bit <<= 1;
    }


Improve Article

Save Article

  • Read
  • Discuss
  • Improve Article

    Save Article

    Error is the fault or mistake in a program. It can be several types. Error can occur due to wrong syntax or wrong logic. It is a type of mistakes or condition of having incorrect knowledge of the code.

    There are various types of errors in PHP but it contains basically four main type of errors.

    1. Parse error or Syntax Error: It is the type of error done by the programmer in the source code of the program. The syntax error is caught by the compiler. After fixing the syntax error the compiler compile the code and execute it. Parse errors can be caused dues to unclosed quotes, missing or Extra parentheses, Unclosed braces, Missing semicolon etc
      Example:

      <?php

      $x = "geeks";

      y = "Computer science";

      echo $x;

      echo $y;

      ?>

      Error:

      PHP Parse error:  syntax error, unexpected '=' 
      in /home/18cb2875ac563160a6120819bab084c8.php on line 3
      

      Explanation: In above program, $ sign is missing in line 3 so it gives an error message.

    2. Fatal Error: It is the type of error where PHP compiler understand the PHP code but it recognizes an undeclared function. This means that function is called without the definition of function.
      Example:

      <?php

      function add($x, $y)

      {

          $sum = $x + $y;

          echo "sum = " . $sum;

      }

      $x = 0;

      $y = 20;

      add($x, $y);

      diff($x, $y);

      ?>

      Error:

      PHP Fatal error:  Uncaught Error: 
      Call to undefined function diff() 
      in /home/36db1ad4634ff7deb7f7347a4ac14d3a.php:12
      
      Stack trace:
      #0 {main}
        thrown in /home/36db1ad4634ff7deb7f7347a4ac14d3a.php on line 12
      

      Explanation : In line 12, function is called but the definition of function is not available. So it gives error.

    3. Warning Errors : The main reason of warning errors are including a missing file. This means that the PHP function call the missing file.
      Example:

      <?php 

      $x = "GeeksforGeeks";

      include ("gfg.php");

      echo $x . "Computer science portal";

      ?>

      Error:

      PHP Warning:  include(gfg.php): failed to 
      open stream: No such file or directory in 
      /home/aed0ed3b35fece41022f332aba5c9b45.php on line 5
      PHP Warning:  include(): Failed opening 'gfg.php'
       for inclusion (include_path='.:/usr/share/php') in 
      /home/aed0ed3b35fece41022f332aba5c9b45.php on line 5
      

      Explanation: This program call an undefined file gfg.php which are not available. So it produces error.

    4. Notice Error: It is similar to warning error. It means that the program contains something wrong but it allows the execution of script.
      Example:

      <?php 

      $x = "GeeksforGeeks";

      echo $x;

      echo $geeks;

      ?>

      Error:

      PHP Notice:  Undefined variable: geeks in 
      /home/84c47fe936e1068b69fb834508d59689.php on line 5
      

      Output:

      GeeksforGeeks
      

      Explanation: This program use undeclared variable $geeks so it gives error message.

    PHP error constants and their description :

    • E_ERROR : A fatal error that causes script termination
    • E_WARNING : Run-time warning that does not cause script termination
    • E_PARSE : Compile time parse error.
    • E_NOTICE : Run time notice caused due to error in code
    • E_CORE_ERROR : Fatal errors that occur during PHP’s initial startup (installation)
    • E_CORE_WARNING : Warnings that occur during PHP’s initial startup
    • E_COMPILE_ERROR : Fatal compile-time errors indication problem with script.
    • E_USER_ERROR : User-generated error message.
    • E_USER_WARNING : User-generated warning message.
    • E_USER_NOTICE : User-generated notice message.
    • E_STRICT : Run-time notices.
    • E_RECOVERABLE_ERROR : Catchable fatal error indicating a dangerous error
    • E_DEPRECATED : Run-time notices.

    A PHP Error occurs when something is wrong in the PHP code. The error can be as simple as a missing semicolon, or as complex as calling an incorrect variable.

    To efficiently resolve a PHP issue in a script, you must understand what kind of problem is occurring.

    tutorial on types of php errors

    The four types of PHP errors are:

    1. Warning Error
    2. Notice Error
    3. Parse Error
    4. Fatal Error

    Tip: You can test your PHP scripts online. We used an online service to test the code mentioned in this article.

    A warning error in PHP does not stop the script from running. It only warns you that there is a problem, one that is likely to cause bigger issues in the future.

    The most common causes of warning errors are:

    • Calling on an external file that does not exist in the directory
    • Wrong parameters in a function

    For instance:

    <?php
    echo "Warning error"';
    include ("external_file.php");
    ?>

    As there is no “external_file”, the output displays a message, notifying it failed to include it. Still, it doesn’t stop executing the script.

    example of warning error

    Notice Error

    Notice errors are minor errors. They are similar to warning errors, as they also don’t stop code execution. Often, the system is uncertain whether it’s an actual error or regular code. Notice errors usually occur if the script needs access to an undefined variable.

    Example:

    <?php
    $a="Defined error";
    echo "Notice error";
    echo $b;
    ?>

    In the script above, we defined a variable ($a), but called on an undefined variable ($b). PHP executes the script but with a notice error message telling you the variable is not defined.

    example of php notice error

    Parse Error (Syntax)

    Parse errors are caused by misused or missing symbols in a syntax. The compiler catches the error and terminates the script.

    Parse errors are caused by:

    • Unclosed brackets or quotes
    • Missing or extra semicolons or parentheses
    • Misspellings

    For example, the following script would stop execution and signal a parse error:

    <?php
    echo "Red";
    echo "Blue";
    echo "Green"
    ?>

    It is unable to execute because of the missing semicolon in the third line.

    example of parse error in php

    Fatal Error

    Fatal errors are ones that crash your program and are classified as critical errors. An undefined function or class in the script is the main reason for this type of error.

    There are three (3) types of fatal errors:

    1. Startup fatal error (when the system can’t run the code at installation)
    2. Compile time fatal error (when a programmer tries to use nonexistent data)
    3. Runtime fatal error (happens while the program is running, causing the code to stop working completely)

    For instance, the following script would result in a fatal error:

    <?php
    function sub()
    {
    $sub=6-1;
    echo "The sub= ".$sub;
    }
    div();
    ?>

    The output tells you why it is unable to compile, as in the image below:

    example of fatal error in php

    Conclusion

    Distinguishing between the four types of PHP errors can help you quickly identify and solve problems in your script. Make sure to pay attention to output messages, as they often report on additional issues or warnings. If you are trying to locate a bug on your website, it is also important to know which PHP version your web server is running.

    PHP is the language used to build websites on the internet for over ten years. Although, there are a lot of people who think that it’s time to move into something else, PHP is a dynamic programming language, which means that it can be adapted to the current needs. And the PHP Core team has been excellent in bringing out new features that make PHP an attractive language in this time and age.

    The flexibility in the PHP language makes it easy to handle things like exceptions in code, which are the out of the ordinary scenarios that can occur. They can be caused by some unexpected input, a bug, or some other problem. PHP 8 is a new version of this language that was released on 26 November 2020. The new version has been adapted to be more secure and handle exceptions better than the previous versions.

    Potential exceptions/errors are enclosed inside a try block if exception is encountered, will be thrown to catch or finally block. PHP usually handles exceptions in a separate catch block for each different type of exception.

    In this post, you can gain knowledge about what exactly is exception handling, and how it works.

    Below are the topics that shall be covered in this blog:

    1. When, Where, and How to use Exceptions and Errors in PHP?
    2. Error Class

    3. Exception Class

    4. Custom Exception

    5. Multiple Exception

    6. Global Exception Handler

    7. Non-Capturing Catches

    #1 When, Where, and How to use Exceptions and Errors in PHP?

    PHP 7 introduced the new Throwable interface to unite the exception branches Exception and Error. The entire PHP exception hierarchy is as follows:

    interface Throwable
        |- Error implements Throwable
            |- CompileError extends Error
                |- ParseError extends CompileError
            |- TypeError extends Error
                |- ArgumentCountError extends TypeError
            |- ArithmeticError extends Error
                |- DivisionByZeroError extends ArithmeticError
            |- AssertionError extends Error
        |- Exception implements Throwable
            |- ClosedGeneratorException
            |- DOMException
            |- ErrorException
            |- IntlException
            |- LogicException
                |- BadFunctionCallException
                    |- BadMethodCallException
                |- DomainException
                |- InvalidArgumentException
                |- LengthException
                |- OutOfRangeException
            |- PharExceptionaddition
            |- ReflectionException
            |- RuntimeException
                |- mysqli_sql_exception
                |- OutOfBoundsException
                |- OverflowException
                |- PDOException
                |- RangeException
                |- UnderflowException
                |- UnexpectedValueException
            |- Custom Exception
    

    To catch both exceptions and errors in PHP 8, add a catch block for Exception after catching Throwable first.

    try 
    { 
        // Code that may throw an Exception or Error. 
    } catch (Throwable $t) 
    { 
       // Executed only in PHP 7 and more
    }

    #2 Error Class

    Error Class is the base class for all internal PHP errors. Errors can be caught in  try/catch block as explained above. Few errors will throw a specific subclass of Error such as Parse Error, Type Error, and so on.

    Here are the list of various types of errors (we have covered only the most common ones):

    1. Parse/Syntax Error
    2. Type Error

    3. Arithmetic Error
    4. Assertion Error

    5. Value Error

    a. Parse/Syntax Error

    A syntax/parse error in the code while compilation, a Parse error is thrown. If a code contains an error, the PHP parser cannot interpret the code and it stops working.

    Let’s look into a simple example for understanding Parse error.

    Code:

    <?php
        $x = "Exception";
        y = "Handling";
        echo $x . ' ' . y;
    ?>

    Output:

    syntax error, unexpected '=' in line 3

    b. Type Error

    When data type mismatch happens in PHP while doing an operation, a Type error is thrown. There are three scenarios where this type of error is thrown:

    • Invalid number of arguments passed to a built-in function.
    • Value returned from a function doesn’t match the declared function return type.
    • Argument type passed to a function doesn’t match the declared parameter type.

    Let’s look into a simple example for understanding Type error.

    Code:

    <?php
    function add(int $x, int $y)
    {
        return $x + $y;
    }
    try {
        $value = add('Type', 10);
    }
    catch (TypeError $e) {
        echo $e->getMessage(), "n";
    }
    ?>

    Output:

    Argument 1 passed to add() must be of the type integer, string given.

    c. Arithmetic Error

    Occurrence of error while performing a mathematical operation, bit shifting by a negative number or calling an intdiv() function, the Arithmetic error is thrown.

    Example With Division Operator:

    <?php
    try {
        intdiv(PHP_INT_MIN, -1);
    }
    catch (ArithmeticError $e) {
        echo $e->getMessage();
    }
    ?>

    Output:

    Division of PHP_INT_MIN by -1 is not an integer

    Example With Modulo Operator:

    <?php
    try {
        $x = 4;
        $y = 0;
        $result = $x%$y;
    }
    catch (DivisionByZeroError $e) {
       echo $e->getMessage();
    }
    ?>

    Output:

    Modulo by zero error

    Example With Division Operator Which Returns INF:

    <?php
    try {
        $x      = 4;
        $y      = 0;
        $result = $x / $y;
    }
    catch (DivisionByZeroError $e) {
        echo $e->getMessage();
    }
    ?>

    Output:

    INF

    Explanation:

    There is a very minute difference in the above two examples. The first one contains the Modulo operator and the second one has the  Division operator. If any variable divided by zero will return an error, Division by zero error. When any variable divided by zero with modulo operator returns Modulo by zero error and the variable divided by zero with the division operator also returns anyone the following- INF, NAN, -INF

    d. Assertion Error

    When an assert() call fails or let’s say when the condition inside the assert() call doesn’t meet, the Assertion error is thrown. String description emits E_DEPRECATED message from PHP 7.2 version. The Assertion Error thrown by assert() will be sent to catch block only if assert.exception=on is enabled in php.ini.

    Let’s look into a simple example for understanding assertion error.

    Code:

    <?php
    try {
        $x      = 1;
        $y      = 2;
        $result = assert($x === $y);
        if (!$result) {
            throw new DivisionByZeroError('Assertion error');
        }
    }
    catch (AssertionError $e) {
        echo $e->getMessage();
    }
    ?>

    Output:

    Assertion error

    e. Value Error

    When the type of the argument is correct and the value of it is incorrect, a value error is thrown. These type of errors occurs when:

    • Passing a negative value when the function expects a positive value.
    • Passing an empty string or array when function expects a non-empty string/array.

    Let’s look into a simple examples for understanding value error.

    Code:

    <?php
        $x = strpos("u", "austin", 24);
        var_dump($x);
    ?>

    Output:

    [Mon Feb 22 20:59:04 2021] 
    PHP Warning:  strpos(): Offset not contained in string in /home/ubuntu/value_error.php on line 2

    Code:

    <?php
        $x = array_rand(array(), 0);
        var_dump($x);
    ?>
    [Mon Feb 22 21:04:14 2021] PHP Warning:  array_rand(): Array is empty in /home/ubuntu/index.php on line 2
    

    #3 Exception Class

    Exception Class occurs when a specified/exceptional error condition changes the normal flow of the code execution.

    Exception handling comprises five components i.e, try block, exception, throw, catch block, and finally block.

    Let’s look into a simple example for understanding the above-mentioned components

    Code:

    <?php
    function add($x,$y) {
        if (is_numeric($x) == False) {
            throw new Exception('Num1  is not a number');
        }
        if (is_numeric($y) == False) {
            throw new RuntimeException('Num2 is not a number');
        }
        return $x + $y;
    }
    
    try {
        echo add(5,10). "n";
        echo add(5,k). "n";
    } 
    
    catch (Exception $e) {
        echo 'Exception caught: ', $e->getMessage(), "n";
    } 
    
    finally {
        echo "Finally Block.n";
    }
    
    // Continue execution
    echo "Hello Worldn";
    ?>

    Output:

    15
    Exception caught: Num2 is not a number
    Finally Block.
    Hello World
    

    Explanation:

    Our example is about adding two numbers and we assumed that we might get non-numeric value as input which would raise an error.

    • We created a function called addition with Exception for non-numeric values and If encountered with the exception, will throw it with the exception message.

    • We called the addition function inside a Try block so that non-numeric value error won’t affect/stop the whole execution. All potential exceptions should be enclosed inside a try block.

    • The Catch block will receive any exceptions thrown from the try block and execute the code inside the block. In our case will print the error message ‘Caught exception: Num2 is not a number’.

    • The Finally block will be executed irrespective of whether we received exception or not.

    #4 Custom Exception

    We use custom exception to make it clear what is being caught in the catch block and to understand the exception in a better way. The custom exception class inherits properties from the PHP exception’s class where you can add your custom functions too. To easily understand the exceptions we can use custom exceptions and can log it for the future use.

    If you just want to capture a message, you can do it at follows:

    try {
        throw new Exception("This is an error message");
    }
    catch(Exception $e) {
        print $e->getMessage();
    }
    

    If you want to capture specific error messages which could be easy to understand you can use:

    try {
        throw new MyException("Error message");
    }
    catch(MyException $e) {
        print "Exception caught: ".$e->getMessage();
    }
    catch(Exception $e) {
        print "Error: ".$e->getMessage();
    }
    

    Code:

    <?php
    
    class customStringException extends Exception
    {
        public function myerrorMessage()
        {
            //error message
            $errorMsg = 'Error on line ' . $this->getLine() . ': <b>' . $this->getMessage() . '</b> is not a String';
            return $errorMsg;
        }
    }
    
    class customNumericException extends Exception
    {
        public function myerrorMessage()
        {
            //error message
            $errorMsg = 'Error on line ' . $this->getLine() . ': <b>' . $this->getMessage() . '</b> is not an Integer';
            return $errorMsg;
        }
    }
    
    function typeCheck($name, $age)
    {
        if (!is_string($name)) {
            throw new customStringException($name);
        }
        if (!is_numeric($age)) {
            throw new customNumericException($age);
        } else {
            echo $name . " is of age " . $age;
        }
    }
    
    try {
        echo typeCheck("Sara", 25) . "n";
        echo typeCheck(5, 10) . "n";
    }
    catch (customStringException $e) {
        echo $e->myerrorMessage();
    }
    catch (customNumericException $e) {
        echo $e->myerrorMessage();
    }
    
    ?>

    Output:

    Sara is of age 25
    Error on line 21: 5 is not a String

    Explanation:

    The above example is on a type check, we have two variables name and age . Let’s assume $name is of type string and $age is of type integer and we assumed that we might get any type of value as input which would raise an error.

    • We created a function called typeCheck to check the type of the variable with exception. If the condition fails it will throw an exception with an Exception message that we have customized.

    • We created a class customStringException to create a custom exception handler with a function called errorMessage which would be called when an exception occurs.

    • Here we called the typeCheck function inside a try block so that if any error is encountered it could be caught in the catch block.

    #5 Multiple Exception

    You can also handle multiple exception in a single catch block using the pipe ‘|’ symbol like this:

    try {
        $error = "Foo / Bar / Baz Exception"; throw new MyBazException($error); 
    } 
    catch(MyFooException | MyBarException | MyBazException $e) { 
        //Do something here 
    }

    #6 Global Exception Handler

    In Global Exception Handler, it sets the default exception handler if an exception is not caught within a try/catch block. If no other block is invoked the set_exception_handler function can set a function which will be called in the place of catch. Execution will stop after the exception_handler is called.

    set_exception_handler Syntax:

    set_exception_handler ( callable $exception_handler ) : callable

    <?php
    
    function exception_handler($exception)
    {
        echo "Uncaught exception: ", $exception->getMessage(), "n";
    }
    
    set_exception_handler('exception_handler');
    
    throw new Exception('Uncaught Exception');
    
    echo "Not Executedn";
    ?>
    

    #7 Non-Capturing Catches

    Before PHP version 8, if you wanna catch an exception you will need to store it in a variable irrespective of its usage. You usually must specify the type whenever you use a catch exception. With this Non-Capturing Catch exception, you can ignore the variable.

    Example:

    try {
        // Something goes wrong
    } 
    catch (MyException $exception) {
        Log::error("Something went wrong");
    }

    You can put it this way in PHP 8:

    try {
        // Something goes wrong
    } 
    catch (MyException) {
        Log::error("Something went wrong");
    }

    Summary:

    Here we have explained the basic usage of exceptions and how to implement it in detail.You can quickly track the errors and fix the exceptions that have been thrown in your code. I hope this blog might be useful for you to learn what exception is and the correct usage of it.

    If you would like to monitor your PHP code, you can try Atatus here.

    PHP reports errors in response to a number of internal error conditions.
    These may be used to signal a number of different conditions, and can be
    displayed and/or logged as required.

    Every error that PHP generates includes a type. A
    list of these types is available,
    along with a short description of their behaviour and how they can be
    caused.

    Handling errors with PHP

    If no error handler is set, then PHP will handle any errors that occur
    according to its configuration. Which errors are reported and which are
    ignored is controlled by the
    error_reporting
    php.ini directive, or at runtime by calling
    error_reporting(). It is strongly recommended that the
    configuration directive be set, however, as some errors can occur before
    execution of your script begins.

    In a development environment, you should always set
    error_reporting
    to E_ALL, as you need to be aware of and fix the
    issues raised by PHP. In production, you may wish to set this to a less
    verbose level such as
    E_ALL & ~E_NOTICE & ~E_STRICT & ~E_DEPRECATED, but
    in many cases E_ALL is also appropriate, as it may
    provide early warning of potential issues.

    What PHP does with these errors depends on two further php.ini directives.
    display_errors
    controls whether the error is shown as part of the script’s output. This
    should always be disabled in a production environment, as it can include
    confidential information such as database passwords, but is often useful to
    enable in development, as it ensures immediate reporting of issues.

    In addition to displaying errors, PHP can log errors when the
    log_errors
    directive is enabled. This will log any errors to the file or syslog
    defined by
    error_log. This
    can be extremely useful in a production environment, as you can log errors
    that occur and then generate reports based on those errors.

    User error handlers

    If PHP’s default error handling is inadequate, you can also handle many
    types of error with your own custom error handler by installing it with
    set_error_handler(). While some error types cannot be
    handled this way, those that can be handled can then be handled in the way
    that your script sees fit: for example, this can be used to show a custom
    error page to the user and then report more directly than via a log, such
    as by sending an e-mail.

    Вернуться к: Errors

    PHP Error Types



    An error is a unwanted result of program. Error is a type of mistake.
    An error can also be defined as generate wrong output of program caused by a fault.
    An error message display with error message, filename and line number.

    An error can be categorized in :

    • Syntax Error
    • Logical Error
    • Run-time Error

    The syntax error is a any mistake in symbol or missing symbol in a syntax.
    Logical error means you expressed something that is logically incorrect and it will produce unwanted result.
    The logical error occur at run-time.
    The run-time error produced by a logical error. Both logical error and run-time error are same thing.

    In PHP there are four types of errors.

    • Notice Error
    • Fatal Error
    • Waring Error
    • Parse Error

    PHP – Notice Error

    Notice error occurs when we use a variable in program which is not defined then it produce notice error.

    Notice error code execution of script does not stop.

    Notice Error Example

    <?php
    
    for($i=1;$i<=10;$i++)
    { 
    $series=$series. " ".$i;
    }
    
    echo "The No = ".$series;
    
    ?>

    The out put of notice error :

    PHP_notice_error

    PHP Notice Error Example

    In above example we use $series variable but it is not defined, so it will produce notice error but the execution of script does not stop.

    PHP Notice Error Example

    <?php

    $a=5;
    echo “The result = ” . $b;

    ?>

    The out put of php example : In this php example we declare a variable $a, but we use another variable $b in program which is not defined, so it will also generate notice error like below.

    PHP Notice Error Example

    PHP Notice Error Example

    PHP – Fatal Error

    Fatal error is critical error and it is stop the execution of script immediately.
    Fatal error occurs when we call undefined functions or class.

    Fatal Error Example

    <?php
    
    function sum()
    {
    $sum=5+6;
    echo "The sum= ".$sum;
    }
    mul();
    
    ?>

    The output o example :

    PHP Fatal Error Example

    PHP Fatal Error Example

    In above example we declined “sum()” function but in program we call “mul()” function which is not defined in program, so it will produce fatal error and stop the execution of script.


    PHP – Warning Error

    A warning error does not stop the execution of script. warning error not a critical error.
    A warning error occurs when we pass wrong parameter in function or we include external file using include() function but the file doesn’t exist then display warning error.

    Warning Error Example

    <?php
    
    include("wrongfile.php");
    $sum=5+6;
    echo "The sum= ".$sum;
    
    ?>

    The out put of php example :

    PHP  Warning Error Example

    PHP Warning Error Example

    PHP – Parse Error

    A Parse error occurs if there is a mistake in a syntax. When parse error occurs the execution of script will be terminated.

    Parse Error Example

    <?php
    
    $a=10;
    $b=5
    echo "The A = ".$a." and B = ". $b;
    
    ?>

    Above example we declare two variable $a and $b, but in $b variable we missing the semicolon(;) so it will produce parse error like below.

    The out put of php example :

    PHP Parse Error Example

    PHP Parse Error Example

    Антон Шевчук // Web-разработчик

    Не совершает ошибок только тот, кто ничего не делает, и мы тому пример – трудимся не покладая рук над созданием рабочих мест для тестировщиков :)

    О да, в этой статье я поведу свой рассказа об ошибках в PHP, и том как их обуздать.

    Ошибки

    Разновидности в семействе ошибок

    Перед тем как приручать ошибки, я бы рекомендовал изучить каждый вид и отдельно обратить внимание на самых ярких представителей.

    Чтобы ни одна ошибка не ушла незамеченной потребуется включить отслеживание всех ошибок с помощью функции error_reporting(), а с помощью директивы display_errors включить их отображение:

    <?php
    error_reporting(E_ALL);
    ini_set('display_errors', 1);
    

    Фатальные ошибки

    Самый грозный вид ошибок – фатальные, они могут возникнуть как при компиляции, так и при работе парсера или PHP-скрипта, выполнение скрипта при этом прерывается.

    E_PARSE
    Это ошибка появляется, когда вы допускаете грубую ошибку синтаксиса и интерпретатор PHP не понимает, что вы от него хотите, например если не закрыли фигурную или круглую скобочку:

    <?php
    /**
     Parse error: syntax error, unexpected end of file
     */
    {
    

    Или написали на непонятном языке:

    <?php
    /**
     Parse error: syntax error, unexpected '...' (T_STRING)
     */
    Тут будет ошибка парсера
    

    Лишние скобочки тоже встречаются, и не важно круглые либо фигурные:

    <?php
    /**
     Parse error: syntax error, unexpected '}'
     */
    }
    

    Отмечу один важный момент – код файла, в котором вы допустили parse error не будет выполнен, следовательно, если вы попытаетесь включить отображение ошибок в том же файле, где возникла ошибка парсера то это не сработает:

    <?php
    // этот код не сработает
    error_reporting(E_ALL);
    ini_set('display_errors', 1);
    
    // т.к. вот тут
    ошибка парсера
    

    E_ERROR
    Это ошибка появляется, когда PHP понял что вы хотите, но сделать сие не получилось ввиду ряда причин, так же прерывает выполнение скрипта, при этом код до появления ошибки сработает:

    Не был найден подключаемый файл:

    /**
     Fatal error: require_once(): Failed opening required 'not-exists.php' (include_path='.:/usr/share/php:/usr/share/pear')
     */
    require_once 'not-exists.php';
    

    Было брошено исключение (что это за зверь, расскажу немного погодя), но не было обработано:

    /**
     Fatal error: Uncaught exception 'Exception'
     */
    throw new Exception();
    

    При попытке вызвать несуществующий метод класса:

    /**
     Fatal error: Call to undefined method stdClass::notExists()
     */
    $stdClass = new stdClass();
    $stdClass->notExists();
    

    Отсутствия свободной памяти (больше, чем прописано в директиве memory_limit) или ещё чего-нить подобного:

    /**
     Fatal Error: Allowed Memory Size
     */
    $arr = array();
    
    while (true) {
        $arr[] = str_pad(' ', 1024);
    }
    

    Очень часто происходит при чтении либо загрузки больших файлов, так что будьте внимательны с вопросом потребляемой памяти

    Рекурсивный вызов функции. В данном примере он закончился на 256-ой итерации, ибо так прописано в настройках xdebug:

    /**
     Fatal error: Maximum function nesting level of '256' reached, aborting!
     */
    function deep() {
        deep();
    }
    deep();
    

    Не фатальные

    Данный вид не прерывает выполнение скрипта, но именно их обычно находит тестировщик, и именно они доставляют больше всего хлопот у начинающих разработчиков.

    E_WARNING
    Частенько встречается, когда подключаешь файл с использованием include, а его не оказывается на сервере или ошиблись указывая путь к файлу:

    /**
     Warning: include_once(): Failed opening 'not-exists.php' for inclusion
     */
    include_once 'not-exists.php';
    

    Бывает, если используешь неправильный тип аргументов при вызове функций:

    /**
     Warning: join(): Invalid arguments passed
     */
    join('string', 'string');
    

    Их очень много, и перечислять все не имеет смысла…

    E_NOTICE
    Это самые распространенные ошибки, мало того, есть любители отключать вывод ошибок и клепают их целыми днями. Возникают при целом ряде тривиальных ошибок.

    Когда обращаются к неопределенной переменной:

    /**
     Notice: Undefined variable: a
     */
    echo $a;
    

    Когда обращаются к несуществующему элементу массива:

    <?php
    /**
     Notice: Undefined index: a
     */
    $b = array();
    $b['a'];
    

    Когда обращаются к несуществующей константе:

    /**
     Notice: Use of undefined constant UNKNOWN_CONSTANT - assumed 'UNKNOWN_CONSTANT'
     */
    echo UNKNOWN_CONSTANT;
    

    Когда не конвертируют типы данных:

    /**
     Notice: Array to string conversion
     */
    echo array();
    

    Для избежания подобных ошибок – будьте внимательней, и если вам IDE подсказывает о чём-то – не игнорируйте её:

    PHP E_NOTICE in PHPStorm

    E_STRICT
    Это ошибки, которые научат вас писать код правильно, чтобы не было стыдно, тем более IDE вам эти ошибки сразу показывают. Вот например, если вызвали не статический метод как статику, то код будет работать, но это как-то неправильно, и возможно появление серьёзных ошибок, если в дальнейшем метод класса будет изменён, и появится обращение к $this:

    /**
     Strict standards: Non-static method Strict::test() should not be called statically
     */
    class Strict { 
        public function test() { 
            echo 'Test'; 
        } 
    }
    
    Strict::test();
    

    E_DEPRECATED
    Так PHP будет ругаться, если вы используете устаревшие функции (т.е. те, что помечены как deprecated, и в следующем мажорном релизе их не будет):

    /**
     Deprecated: Function split() is deprecated
     */
    
    // популярная функция, всё никак не удалят из PHP
    // deprecated since 5.3
    split(',', 'a,b');
    

    В моём редакторе подобные функции будут зачёркнуты:

    PHP E_DEPRECATED in PHPStorm

    Обрабатываемые

    Этот вид, которые разводит сам разработчик кода, я их уже давно не встречал, не рекомендую их вам заводить:

    • E_USER_ERROR – критическая ошибка
    • E_USER_WARNING – не критическая ошибка
    • E_USER_NOTICE – сообщения которые не являются ошибками

    Отдельно стоит отметить E_USER_DEPRECATED – этот вид всё ещё используется очень часто для того, чтобы напомнить программисту, что метод или функция устарели и пора переписать код без использования оной. Для создания этой и подобных ошибок используется функция trigger_error():

    /**
     * @deprecated Deprecated since version 1.2, to be removed in 2.0
     */
    function generateToken() {
        trigger_error('Function `generateToken` is deprecated, use class `Token` instead', E_USER_DEPRECATED);
        // ...
        // code ...
        // ...
    }
    

    Теперь, когда вы познакомились с большинством видов и типов ошибок, пора озвучить небольшое пояснение по работе директивы display_errors:

    • если display_errors = on, то в случае ошибки браузер получит html c текстом ошибки и кодом 200
    • если же display_errors = off, то для фатальных ошибок код ответа будет 500 и результат не будет возвращён пользователю, для остальных ошибок – код будет работать неправильно, но никому об этом не расскажет

    Приручение

    Для работы с ошибками в PHP существует 3 функции:

    • set_error_handler() — устанавливает обработчик для ошибок, которые не обрывают работу скрипта (т.е. для не фатальных ошибок)
    • error_get_last() — получает информацию о последней ошибке
    • register_shutdown_function() — регистрирует обработчик который будет запущен при завершении работы скрипта. Данная функция не относится непосредственно к обработчикам ошибок, но зачастую используется именно для этого

    Теперь немного подробностей об обработке ошибок с использованием set_error_handler(), в качестве аргументов данная функция принимает имя функции, на которую будет возложена миссия по обработке ошибок и типы ошибок которые будут отслеживаться. Обработчиком ошибок может так же быть методом класса, или анонимной функцией, главное, чтобы он принимал следующий список аргументов:

    • $errno – первый аргумент содержит тип ошибки в виде целого числа
    • $errstr – второй аргумент содержит сообщение об ошибке
    • $errfile – необязательный третий аргумент содержит имя файла, в котором произошла ошибка
    • $errline – необязательный четвертый аргумент содержит номер строки, в которой произошла ошибка
    • $errcontext – необязательный пятый аргумент содержит массив всех переменных, существующих в области видимости, где произошла ошибка

    В случае если обработчик вернул true, то ошибка будет считаться обработанной и выполнение скрипта продолжится, иначе — будет вызван стандартный обработчик, который логирует ошибку и в зависимости от её типа продолжит выполнение скрипта или завершит его. Вот пример обработчика:

    <?php
        // включаем отображение всех ошибок, кроме E_NOTICE
        error_reporting(E_ALL & ~E_NOTICE);
        ini_set('display_errors', 1);
        
        // наш обработчик ошибок
        function myHandler($level, $message, $file, $line, $context) {
            // в зависимости от типа ошибки формируем заголовок сообщения
            switch ($level) {
                case E_WARNING:
                    $type = 'Warning';
                    break;
                case E_NOTICE:
                    $type = 'Notice';
                    break;
                default;
                    // это не E_WARNING и не E_NOTICE
                    // значит мы прекращаем обработку ошибки
                    // далее обработка ложится на сам PHP
                    return false;
            }
            // выводим текст ошибки
            echo "<h2>$type: $message</h2>";
            echo "<p><strong>File</strong>: $file:$line</p>";
            echo "<p><strong>Context</strong>: $". join(', $', array_keys($context))."</p>";
            // сообщаем, что мы обработали ошибку, и дальнейшая обработка не требуется
            return true;
        }
        
        // регистрируем наш обработчик, он будет срабатывать на для всех типов ошибок
        set_error_handler('myHandler', E_ALL);
    

    У вас не получится назначить более одной функции для обработки ошибок, хотя очень бы хотелось регистрировать для каждого типа ошибок свой обработчик, но нет – пишите один обработчик, и всю логику отображения для каждого типа описывайте уже непосредственно в нём

    С обработчиком, который написан выше есть одна существенная проблема – он не ловит фатальные ошибки, и вместо сайта пользователи увидят лишь пустую страницу, либо, что ещё хуже, сообщение об ошибке. Дабы не допустить подобного сценария следует воспользоваться функцией register_shutdown_function() и с её помощью зарегистрировать функцию, которая всегда будет выполняться по окончанию работы скрипта:

    function shutdown() {
        echo 'Этот текст будет всегда отображаться';
    }
    register_shutdown_function('shutdown');
    

    Данная функция будет срабатывать всегда!

    Но вернёмся к ошибкам, для отслеживания появления в коде ошибки воспользуемся функцией error_get_last(), с её помощью можно получить информацию о последней выявленной ошибке, а поскольку фатальные ошибки прерывают выполнение кода, то они всегда будут выполнять роль “последних”:

    function shutdown() {
        $error = error_get_last();
        if (
            // если в коде была допущена ошибка
            is_array($error) &&
            // и это одна из фатальных ошибок
            in_array($error['type'], [E_ERROR, E_PARSE, E_CORE_ERROR, E_COMPILE_ERROR])
        ) {
            // очищаем буфер вывода (о нём мы ещё поговорим в последующих статьях)
            while (ob_get_level()) {
                ob_end_clean();
            }
            // выводим описание проблемы
            echo 'Сервер находится на техническом обслуживании, зайдите позже';
        }
    }
    register_shutdown_function('shutdown');
    

    Задание
    Дополнить обработчик фатальных ошибок выводом исходного кода файла где была допущена ошибка, а так же добавьте подсветку синтаксиса выводимого кода.

    О прожорливости

    Проведём простой тест, и выясним – сколько драгоценных ресурсов кушает самая тривиальная ошибка:

    /**
     * Этот код не вызывает ошибок
     */
    
    // сохраняем параметры памяти и времени выполнения скрипта
    $memory = memory_get_usage();
    $time= microtime(true);
    
    $a = '';
    $arr = [];
    for ($i = 0; $i < 10000; $i++) {
        $arr[$a] = $i;
    }
    
    printf('%f seconds <br/>', microtime(true) - $time);
    echo number_format(memory_get_usage() - $memory, 0, '.', ' '), ' bytes<br/>';
    

    В результате запуска данного скрипта у меня получился вот такой результат:

    0.002867 seconds 
    984 bytes
    

    Теперь добавим ошибку в цикле:

    /**
     * Этот код содержит ошибку
     */
    
    // сохраняем параметры памяти и времени выполнения скрипта
    $memory = memory_get_usage();
    $time= microtime(true);
    
    $a = '';
    $arr = [];
    for ($i = 0; $i < 10000; $i++) {
        $arr[$b] = $i; // тут ошиблись с именем переменной
    }
    
    printf('%f seconds <br/>', microtime(true) - $time);
    echo number_format(memory_get_usage() - $memory, 0, '.', ' '), ' bytes<br/>';
    

    Результат ожидаемо хуже, и на порядок (даже на два порядка!):

    0.263645 seconds 
    992 bytes
    

    Вывод однозначен – ошибки в коде приводят к лишней прожорливости скриптов – так что во время разработки и тестирования приложения включайте отображение всех ошибок!

    Тестирование проводил на PHP версии 5.6, в седьмой версии результат лучше – 0.0004 секунды против 0.0050 – разница только на один порядок, но в любом случае результат стоит прикладываемых усилий по исправлению ошибок

    Где собака зарыта

    В PHP есть спец символ «@» – оператор подавления ошибок, его используют дабы не писать обработку ошибок, а положится на корректное поведение PHP в случае чего:

    <?php
        echo @UNKNOWN_CONSTANT;
    

    При этом обработчик ошибок указанный в set_error_handler() всё равно будет вызван, а факт того, что к ошибке было применено подавление можно отследить вызвав функцию error_reporting() внутри обработчика, в этом случае она вернёт 0.

    Если вы в такой способ подавляете ошибки, то это уменьшает нагрузку на процессор в сравнении с тем, если вы их просто скрываете (см. сравнительный тест выше), но в любом случае, подавление ошибок это зло

    Исключения

    В эру PHP4 не было исключений (exceptions), всё было намного сложнее, и разработчики боролись с ошибками как могли, это было сражение не на жизнь, а на смерть… Окунуться в эту увлекательную историю противостояния можете в статье Исключительный код. Часть 1. Стоит ли её читать сейчас? Думаю да, ведь это поможет вам понять эволюцию языка, и раскроет всю прелесть исключений

    Исключения — исключительные событие в PHP, в отличии от ошибок не просто констатируют наличие проблемы, а требуют от программиста дополнительных действий по обработке каждого конкретного случая.

    К примеру, скрипт должен сохранить какие-то данные в кеш файл, если что-то пошло не так (нет доступа на запись, нет места на диске), генерируется исключение соответствующего типа, а в обработчике исключений принимается решение – сохранить в другое место или сообщить пользователю о проблеме.

    Исключение – это объект который наследуется от класса Exception, содержит текст ошибки, статус, а также может содержать ссылку на другое исключение которое стало первопричиной данного. Модель исключений в PHP схожа с используемыми в других языках программирования. Исключение можно инициировать (как говорят, “бросить”) при помощи оператора throw, и можно перехватить (“поймать”) оператором catch. Код генерирующий исключение, должен быть окружен блоком try, для того чтобы можно было перехватить исключение. Каждый блок try должен иметь как минимум один соответствующий ему блок catch или finally:

    try {
        // код который может выбросить исключение
        if (rand(0, 1)) {
            throw new Exception('One')
        } else {
            echo 'Zero';
        }
    } catch (Exception $e) {
        // код который может обработать исключение
        echo $e->getMessage();
    }
    

    В каких случаях стоит применять исключения:

    • если в рамках одного метода/функции происходит несколько операций которые могут завершиться неудачей
    • если используемый вами фреймверк или библиотека декларируют их использование

    Для иллюстрации первого сценария возьмём уже озвученный пример функции для записи данных в файл – помешать нам может очень много факторов, а для того, чтобы сообщить выше стоящему коду в чем именно была проблема необходимо создать и выбросить исключение:

    $directory = __DIR__ . DIRECTORY_SEPARATOR . 'logs';
    
    // директории может не быть
    if (!is_dir($directory)) {
        throw new Exception('Directory `logs` is not exists');
    }
    
    // может не быть прав на запись в директорию
    if (!is_writable($directory)) {
        throw new Exception('Directory `logs` is not writable');
    }
    
    // возможно кто-то уже создал файл, и закрыл к нему доступ
    if (!$file = @fopen($directory . DIRECTORY_SEPARATOR . date('Y-m-d') . '.log', 'a+')) {
        throw new Exception('System can't create log file');
    }
    
    fputs($file, date('[H:i:s]') . " donen");
    fclose($file);
    

    Соответственно ловить данные исключения будем примерно так:

    try {
        // код который пишет в файл
        // ...
    } catch (Exception $e) {
        // выводим текст ошибки
        echo 'Не получилось: '. $e->getMessage();
    }
    

    В данном примере приведен очень простой сценарий обработки исключений, когда у нас любая исключительная ситуация обрабатывается на один манер. Но зачастую – различные исключения требуют различного подхода к обработке, и тогда следует использовать коды исключений и задать иерархию исключений в приложении:

    // исключения файловой системы
    class FileSystemException extends Exception {}
    
    // исключения связанные с директориями
    class DirectoryException extends FileSystemException {
        // коды исключений
        const DIRECTORY_NOT_EXISTS =  1;
        const DIRECTORY_NOT_WRITABLE = 2;
    }
    
    // исключения связанные с файлами
    class FileException extends FileSystemException {}
    

    Теперь, если использовать эти исключения то можно получить следующий код:

    try {
        // код который пишет в файл
        if (!is_dir($directory)) {
            throw new DirectoryException('Directory `logs` is not exists', DirectoryException::DIRECTORY_NOT_EXISTS);
        }
    
        if (!is_writable($directory)) {
            throw new DirectoryException('Directory `logs` is not writable', DirectoryException::DIRECTORY_NOT_WRITABLE);
        }
    
        if (!$file = @fopen($directory . DIRECTORY_SEPARATOR . date('Y-m-d') . '.log', 'a+')) {
            throw new FileException('System can't open log file');
        }
    
        fputs($file, date('[H:i:s]'') . " donen");
        fclose($file);
    } catch (DirectoryException $e) {
        echo 'С директорией возникла проблема: '. $e->getMessage();
    } catch (FileException $e) {
        echo 'С файлом возникла проблема: '. $e->getMessage();
    } catch (FileSystemException $e) {
        echo 'Ошибка файловой системы: '. $e->getMessage();
    } catch (Exception $e) {
        echo 'Ошибка сервера: '. $e->getMessage();
    }
    

    Важно помнить, что Exception — это прежде всего исключительное событие, иными словами исключение из правил. Не нужно использовать их для обработки очевидных ошибок, к примеру, для валидации введённых пользователем данных (хотя тут не всё так однозначно). При этом обработчик исключений должен быть написан в том месте, где он будет способен его обработать. К примеру, обработчик для исключений вызванных недоступностью файла для записи должен быть в методе, который отвечает за выбор файла или методе его вызывающем, для того что бы он имел возможность выбрать другой файл или другую директорию.

    Так, а что будет если не поймать исключение? Вы получите “Fatal Error: Uncaught exception …”. Неприятно.
    Чтобы избежать подобной ситуации следует использовать функцию set_exception_handler() и установить обработчик для исключений, которые брошены вне блока try-catch и не были обработаны. После вызова такого обработчика выполнение скрипта будет остановлено:

    // в качестве обработчика событий 
    // будем использовать анонимную функцию
    set_exception_handler(function($exception) {
        /** @var Exception $exception */
        echo $exception->getMessage(), "<br/>n";
        echo $exception->getFile(), ':', $exception->getLine(), "<br/>n";
        echo $exception->getTraceAsString(), "<br/>n";
    });
    

    Ещё расскажу про конструкцию с использованием блока finally – этот блок будет выполнен вне зависимости от того, было выброшено исключение или нет:

    try {
        // код который может выбросить исключение
    } catch (Exception $e) {
        // код который может обработать исключение
        // если конечно оно появится
    } finally {
        // код, который будет выполнен при любом раскладе
    }
    

    Для понимания того, что это нам даёт приведу следующий пример использования блока finally:

    try {
        // где-то глубоко внутри кода
        // соединение с базой данных
        $handler = mysqli_connect('localhost', 'root', '', 'test');
    
        try {
            // при работе с БД возникла исключительная ситуация
            // ...
            throw new Exception('DB error');
        } catch (Exception $e) {
            // исключение поймали, обработали на своём уровне
            // и должны его пробросить вверх, для дальнейшей обработки
            throw new Exception('Catch exception', 0, $e);
        } finally {
            // но, соединение с БД необходимо закрыть
            // будем делать это в блоке finally
            mysqli_close($handler);
        }
    
        // этот код не будет выполнен, если произойдёт исключение в коде выше
        echo "Ok";
    } catch (Exception $e) {
        // ловим исключение, и выводим текст
        echo $e->getMessage();
        echo "<br/>";
        // выводим информацию о первоначальном исключении
        echo $e->getPrevious()->getMessage();
    }
    

    Т.е. запомните – блок finally будет выполнен даже в том случае, если вы в блоке catch пробрасываете исключение выше (собственно именно так он и задумывался).

    Для вводной статьи информации в самый раз, кто жаждет ещё подробностей, то вы их найдёте в статье Исключительный код ;)

    Задание
    Написать свой обработчик исключений, с выводом текста файла где произошла ошибка, и всё это с подсветкой синтаксиса, так же не забудьте вывести trace в читаемом виде. Для ориентира – посмотрите как это круто выглядит у whoops.

    PHP7 – всё не так, как было раньше

    Так, вот вы сейчас всю информацию выше усвоили и теперь я буду грузить вас нововведениями в PHP7, т.е. я буду рассказывать о том, с чем вы столкнётесь через год работы PHP разработчиком. Ранее я вам рассказывал и показывал на примерах какой костыль нужно соорудить, чтобы отлавливать критические ошибки, так вот – в PHP7 это решили исправить, но как обычно завязались на обратную совместимость кода, и получили хоть и универсальное решение, но оно далеко от идеала. А теперь по пунктам об изменениях:

    1. при возникновении фатальных ошибок типа E_ERROR или фатальных ошибок с возможностью обработки E_RECOVERABLE_ERROR PHP выбрасывает исключение
    2. эти исключения не наследуют класс Exception (помните я говорил об обратной совместимости, это всё ради неё)
    3. эти исключения наследуют класс Error
    4. оба класса Exception и Error реализуют интерфейс Throwable
    5. вы не можете реализовать интерфейс Throwable в своём коде

    Интерфейс Throwable практически полностью повторяет нам Exception:

    interface Throwable
    {
        public function getMessage(): string;
        public function getCode(): int;
        public function getFile(): string;
        public function getLine(): int;
        public function getTrace(): array;
        public function getTraceAsString(): string;
        public function getPrevious(): Throwable;
        public function __toString(): string;
    }
    

    Сложно? Теперь на примерах, возьмём те, что были выше и слегка модернизируем:

    try {
        // файл, который вызывает ошибку парсера
        include 'e_parse_include.php';
    } catch (Error $e) {
        var_dump($e);
    }
    

    В результате ошибку поймаем и выведем:

    object(ParseError)#1 (7) {
      ["message":protected] => string(48) "syntax error, unexpected 'будет' (T_STRING)"
      ["string":"Error":private] => string(0) ""
      ["code":protected] => int(0)
      ["file":protected] => string(49) "/www/education/error/e_parse_include.php"
      ["line":protected] => int(4)
      ["trace":"Error":private] => array(0) { }
      ["previous":"Error":private] => NULL
    }
    

    Как видите – поймали исключение ParseError, которое является наследником исключения Error, который реализует интерфейс Throwable, в доме который построил Джек. Ещё есть другие, но не буду мучать – для наглядности приведу иерархию исключений:

    interface Throwable
      |- Exception implements Throwable
      |    |- ErrorException extends Exception
      |    |- ... extends Exception
      |    `- ... extends Exception
      `- Error implements Throwable
          |- TypeError extends Error
          |- ParseError extends Error
          |- ArithmeticError extends Error
          |  `- DivisionByZeroError extends ArithmeticError
          `- AssertionError extends Error 
    

    TypeError – для ошибок, когда тип аргументов функции не совпадает с передаваемым типом:

    try {
        (function(int $one, int $two) {
            return;
        })('one', 'two');
    } catch (TypeError $e) {
        echo $e->getMessage();
    }
    

    ArithmeticError – могут возникнуть при математических операциях, к примеру когда результат вычисления превышает лимит выделенный для целого числа:

    try {
        1 << -1;
    } catch (ArithmeticError $e) {
        echo $e->getMessage();
    }
    

    DivisionByZeroError – ошибка деления на ноль:

    try {
        1 / 0;
    } catch (ArithmeticError $e) {
        echo $e->getMessage();
    }
    

    AssertionError – редкий зверь, появляется когда условие заданное в assert() не выполняется:

    ini_set('zend.assertions', 1);
    ini_set('assert.exception', 1);
    
    try {
        assert(1 === 0);
    } catch (AssertionError $e) {
        echo $e->getMessage();
    }
    

    При настройках production-серверов, директивы zend.assertions и assert.exception отключают, и это правильно

    Задание
    Написать универсальный обработчик ошибок для PHP7, который будет отлавливать все возможные исключения.

    При написании данного раздела были использованы материалы из статьи Throwable Exceptions and Errors in PHP 7

    Отладка

    Иногда для отладки кода нужно отследить что происходило с переменной или объектом на определённом этапе, для этих целей есть функция debug_backtrace() и debug_print_backtrace() которые вернут историю вызовов функций/методов в обратном порядке:

    <?php
    function example() {
        echo '<pre>';
        debug_print_backtrace();
        echo '</pre>';
    }
    
    class ExampleClass {
        public static function method () {
            example();
        }
    }
    
    ExampleClass::method();
    

    В результате выполнения функции debug_print_backtrace() будет выведен список вызовов приведших нас к данной точке:

    #0  example() called at [/www/education/error/backtrace.php:10]
    #1  ExampleClass::method() called at [/www/education/error/backtrace.php:14]
    

    Проверить код на наличие синтаксических ошибок можно с помощью функции php_check_syntax() или же команды php -l [путь к файлу], но я не встречал использования оных.

    Assert

    Отдельно хочу рассказать о таком экзотическом звере как assert() в PHP, собственно это кусочек контрактной методологии программирования, и дальше я расскажу вам как я никогда его не использовал :)

    Первый случай – это когда вам надо написать TODO прямо в коде, да так, чтобы точно не забыть реализовать заданный функционал:

    // включаем вывод ошибок
    error_reporting(E_ALL);
    ini_set('display_errors', 1);
    
    // включаем asserts
    ini_set('zend.assertions', 1);
    ini_set('assert.active', 1);
    
    assert(false, "Remove it!");
    

    В результате выполнения данного кода получим E_WARNING:

    Warning: assert(): Remove it! failed
    

    PHP7 можно переключить в режим exception, и вместо ошибки будет всегда появляться исключение AssertionError:

    // включаем asserts
    ini_set('zend.assertions', 1);
    ini_set('assert.active', 1);
    // переключаем на исключения
    ini_set('assert.exception', 1);
    
    assert(false, "Remove it!");
    

    В результате ожидаемо получаем не пойманный AssertionError. При необходимости, можно выбрасывать произвольное исключение:

    assert(false, new Exception("Remove it!"));
    

    Но я бы рекомендовал использовать метки @TODO, современные IDE отлично с ними работают, и вам не нужно будет прикладывать дополнительные усилия и ресурсы для работы с ними

    Второй вариант использования – это создание некоего подобия TDD, но помните – это лишь подобие. Хотя, если сильно постараться, то можно получить забавный результат, который поможет в тестировании вашего кода:

    // callback-функция для вывода информации в браузер
    function backlog($script, $line, $code, $message) {
        echo "<h3>$message</h3>";
        highlight_string ($code);
    }
    
    // устанавливаем callback-функцию
    assert_options(ASSERT_CALLBACK, 'backlog');
    // отключаем вывод предупреждений
    assert_options(ASSERT_WARNING,  false);
    
    // пишем проверку и её описание
    assert("sqr(4) == 16", "When I send integer, function should return square of it");
    
    // функция, которую проверяем
    function sqr($a) {
        return; // она не работает
    }
    

    Третий теоретический вариант – это непосредственно контрактное программирование – когда вы описали правила использования своей библиотеки, но хотите точно убедится, что вас поняли правильно, и в случае чего сразу указать разработчику на ошибку (я вот даже не уверен, что правильно его понимаю, но пример кода вполне рабочий):

    /**
     * Настройки соединения должны передаваться в следующем виде
     *
     *     [
     *         'host' => 'localhost',
     *         'port' => 3306,
     *         'name' => 'dbname',
     *         'user' => 'root',
     *         'pass' => ''
     *     ]
     *
     * @param $settings
     */
    function setupDb ($settings) {
        // проверяем настройки
        assert(isset($settings['host']), 'Db `host` is required');
        assert(isset($settings['port']) && is_int($settings['port']), 'Db `port` is required, should be integer');
        assert(isset($settings['name']), 'Db `name` is required, should be integer');
    
        // соединяем с БД
        // ...
    }
    
    setupDb(['host' => 'localhost']);
    

    Никогда не используйте assert() для проверки входных параметров, ведь фактически assert() интерпретирует строковую переменную (ведёт себя как eval()), а это чревато PHP-инъекцией. И да, это правильное поведение, т.к. просто отключив assert’ы всё что передаётся внутрь будет проигнорировано, а если делать как в примере выше, то код будет выполняться, а внутрь отключенного assert’a будет передан булевый результат выполнения

    Если у вас есть живой опыт использования assert() – поделитесь со мной, буду благодарен. И да, вот вам ещё занимательно чтива по этой теме – PHP Assertions, с таким же вопросом в конце :)

    В заключение

    Я за вас напишу выводы из данной статьи:

    • Ошибкам бой – их не должно быть в вашем коде
    • Используйте исключения – работу с ними нужно правильно организовать и будет счастье
    • Assert – узнали о них, и хорошо

    P.S. Спасибо Максиму Слесаренко за помощь в написании статьи

    Types of Error in PHP

    Introduction to Error in PHP

    The event of the occurrence of deviation of the result from the accurate result is termed as an Error. In PHP, error can be generated because of the usage of an incorrect format of coding or implementation of non-feasible functionality. Based on the root cause and level of severity, errors in PHP are categorized in 4 types, such as:

    1. Syntax error (Parse error)
    2. Warning Error
    3. Notice error
    4. Fatal error

    Types of Errors in PHP

    Lets discuss the Types of Error in PHP.

    Types of Errors in PHP 2

    1. Syntax Error (Parse Error)

    In PHP, the scripting needs to follow standard grammar to develop an executable code. When the written code syntax gets deviated from the standard, syntax error takes place. It is also called as parse error. This error gets checked in the compilation stage itself and execution of the code gets stopped. It does not allow the execution unless the error is not fixed and compilation is completed without any syntax flaw. The error constant that is used to represent compile time parse (syntax) error: E_PARSE

    Example:

    The below code snippet is developed to assign values to PHP variables and display the stores values on the output window.

    <?php
    $Correct_Var = "Writing a code to demonstrate Syntax(Parse Error)";
    Incorrect_Var = "The '$' symbol is missing for variable y!!!";
    echo $Correct_Var;
    echo Incorrect_Var;
    ?>

    Output:

    PHP compiler understand existence of any variable when a string is associated with $ symbol. In the above code, definition of variable Incorrect_Var does not satisfy the grammar, hence the compiler throws syntax error for the code and execution is interrupted.

    Types of Error python 1

    2. Warning Error

    This error arises when the PHP script is trying to process any invalid information such as trying to perform a file operation on a file which does not exist or try to call a function with number of input values i.e. different from number of arguments present in the calling function definition. These are serious errors but does not stop the execution of the program and ends in exhibiting unexpected result. The error constant that is used to represent run time warning without terminating script execution: E_WARNING

    Example:

    The below code snippet is written to call another script file within the current programming.

    <?php
    echo "Beginning of program execution";
    echo "<br>";
    echo "<br>";
    $Correct_Var = "Writing a code to demonstrate Warning Error";
    echo $Correct_Var;
    echo "<br>";
    echo "<br>";
    include ("MissingScript.php"); //Calling the script file which is not available
    echo "Ending of program execution";
    ?>

    Output:

    According to the programming, compiler successfully compiled to code and starts execution. The execution continues sequentially. For the command include (“MissingScript.php”), it is looking for the script in the default path …/usr/share/php and does not found any script with the given name. Thus it ends in resulting the warning message for that specific command and execution the rest of the code as designed.

    Types of Error python 2

    3. Notice Error

    This error is encountered in PHP when there is any invalid coding has been developed in the script. This is categorized as non-critical error which does not stop the execution, ends in resulting an error message. The error constant that is used to represent Run time notice message, resulting because of present of invalid code: E_NOTICE

    Example:

    <?php
    echo "Beginning of program execution";
    echo "<br>";
    echo "<br>";
    $Correct_Var = "Writing a code to demonstrate Notice Error";
    echo $InCorrect_Var; //Try to display value stored in an undefined variable
    echo "<br>";
    echo "<br>";
    echo "Ending of program execution";
    ?>

    Output:

    The compiler does not recognize the variable $InCorrect_Var as it is not defined in the code. Hence it throws the Notice error.

    Notice Error

    4. Fatal Error

    A compile time error that is encountered due to any invalid command such as missing of function definition for a calling function, is coined as fatal error. Severity level of this type of error is critical and hence it does not let the execution to be proceed and throw fatal error message as output. The error constant that is used to represent the fatal error which triggers script termination: E_ERROR

    Example:

    The below code snippet is designed to call demonstrate application of function in PHP scripting.

    <?php
    echo "Beginning of program execution";
    echo "<br>";
    echo "<br>";
    $Correct_Var = "Writing a code to demonstrate Fatal Error";
    echo $Correct_Var;
    echo "<br>";
    echo "<br>";
    UndefinedFunction();//Calling a function which is not defined in the script
    echo "Ending of program execution";
    ?>

    Output:

    As the code is developed following the correct coding grammar, it does not catch any error during compilation. In the execution phase it cannot decode the command to call the function UndefinedFunction(), as it is not defined in the scope of the program. Hence it results in throwing the fatal error message and execution of the program is halted.

    Fatal Error 4

    Additional Note

    1. Error handling is easy in PHP. If any developer does not have access to the complete code for any application, it is recommended to use error handling functions in possible scenarios.

    2. In order to avoid new error in the PHP programming, developer is expected to follow proper coding guidelines and stays alert towards probabilities of various types of errors, warnings and notices.

    3. It is recommended not to allow any error or warning or notice to be displayed to the user. Hence the best practice for any safe PHP programming to ensure the required configuration to be available in php.ini file.

    The desired value for the below variables are:

    error_reporting as ' E_ALL'
    display_errors as 'Off'
    log_errors as 'On'

    The below code can be included in any PHP script to configure the desired values in the php.ini file:

    error_reporting(E_ALL);
    ini_set('display_errors','0');
    ini_set('log_errors','1');

    4. PHP incorporates the feature to enable developer to write own customized error handling functions.
    This function needs to be designed with some specific guidelines as follows:

    Function should be capable of handling minimum of two input parameters: error message and error level and maximum of 5 input parameters by including the optional parameters such as line number, file and error context.

    Recommended Articles

    This is a guide to Types of Error in PHP. Here we discuss the introduction and 4 types of errors in PHP along with different examples and code implementation. you may also have a look at the following articles to learn more –

    1. Validation in PHP
    2. PHP Date Time Functions
    3. PHP Data Object
    4. isset() Function in PHP

    Понравилась статья? Поделить с друзьями:
  • Error typeerror cannot read properties of undefined reading push
  • Error typeerror cannot read properties of undefined reading normalmodule
  • Error typeerror cannot read properties of undefined reading nativeelement
  • Error typeerror cannot read properties of undefined reading length
  • Error typed files cannot contain reference counted types