Why does `setcookie` send header before throwing `Error` exception?

From: Date: Sun, 04 Apr 2021 21:53:42 +0000
Subject: Why does `setcookie` send header before throwing `Error` exception?
Groups: php.general 
Request: Send a blank email to php-general+get-327534@lists.php.net to get a copy of this message
Hello PHP team! The following code: <?php class Foo { } setcookie('name', 'value', array( 'expires' => 1, 'path' => new Foo() )); ?> throws an error message that goes like this: PHP Fatal error: Uncaught Error: Object of class Foo could not be converted to string in ... Stack trace: #0 ...: setcookie() #1 {main} thrown in ... so I would expect no Set-Cookie header to be send because of this fatal error. However, after wrapping this code in a try/catch block, I noticed it actually sent the header: Set-Cookie: name=value; expires=Thu, 01-Jan-1970 00:00:01 GMT; Max-Age=0 It looks like the Error exception is thrown somewhere after sending the cookie header. Why does it work in this way? Is it ok? The call above is almost a synonym for this invocation: setcookie('name', 'value', 1, => new Foo()); Except that it does not send the cookie header. I tested it with PHP 8.0.3 on an ArchLinux box; what follows is a test file: --TEST-- setcookie() sends header before throwing Error exception --FILE-- <?php ob_start(); class Foo{ } try { setcookie('name', 'value', array( 'path' => new Foo() )); } catch (\Error $e) { echo $e->getMessage() . "\n"; } var_dump(headers_list()); echo "Done\n"; ?> --EXPECTHEADERS-- --EXPECTF-- Object of class Foo could not be converted to string array(1) { [0]=> string(23) "X-Powered-By: PHP/8.0.3" } Done Thank you very much for your help, Regards, Jair López

« previous php.general (#327534) next »