0

I found a different behaviour when I run the following code in Laravel and in a simple php script.

try { 
    $a=null; $a[3]; 
    var_dump('ok'); 
} catch (\Exception $e) { 
    var_dump('error'); 
}

In Laravel it returns error but in the simple php script it returns ok.

I was wonder how can I set to return error in php script also.

MylesK
  • 3,349
  • 2
  • 9
  • 31
Ali
  • 185
  • 11
  • 1
    I think it is because PHP classifies accessing and array offset on type null as a warning and not an exception. Take a look at this answer where it's explained how to catch warnings: https://stackoverflow.com/questions/1241728/can-i-try-catch-a-warning – geertjanknapen Jul 29 '22 at 10:23
  • @geertjanknapen thank you so much! So my Laravel is turning warnings into exceptions with a code like this: `set_error_handler(function ($severity, $message, $file, $line) { throw new \ErrorException($message, $severity, $severity, $file, $line); });` – Ali Jul 29 '22 at 11:30
  • A bit late but I'm going to answer the question so it can be closed. – geertjanknapen Aug 01 '22 at 05:55

1 Answers1

0

This happens because PHP classifies "accessing an array offset on type null" as a warning and not as an exception. Since you only try to catch exceptions and are given warnings, it will never enter the catch block. Since under the hood Laravel translates warnings into exceptions, the catch block will be entered in Laravel and therefore output error.

This answer will explain how to catch warnings.

Pretty sure you can also try your hand at editing the register() method in Handler.php to create a custom error handler, but there are probably plenty of guides online.

geertjanknapen
  • 1,159
  • 8
  • 23