php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Bug #75824 Inconsistent handling of void/null optional return type hints
Submitted: 2018-01-16 15:14 UTC Modified: 2018-01-16 16:26 UTC
From: adam at nostradamus dot nu Assigned:
Status: Not a bug Package: Scripting Engine problem
PHP Version: 7.1.13 OS: any
Private report: No CVE-ID: None
Welcome back! If you're the original bug submitter, here's where you can edit the bug or add additional notes.
If you forgot your password, you can retrieve your password here.
Password:
Status:
Package:
Bug Type:
Summary:
From: adam at nostradamus dot nu
New email:
PHP Version: OS:

 

 [2018-01-16 15:14 UTC] adam at nostradamus dot nu
Description:
------------
We are running into an issue where a function that does not return any value fails in strict mode when an optional return type hint is applied.

Observe the following php scripts: 
https://3v4l.org/o5ufU
https://3v4l.org/5TIB5

(the only difference is the explicit null return in the second one)

In my opinion, the first one should succeed as well, specifically since the strict check in the following script succeeds: https://3v4l.org/hn6F0

Expected result:
----------------
NULL
int(1)

Actual result:
--------------
Fatal error: Uncaught TypeError: Return value of Foo::getTest() must be of the type integer or null, none returned in /in/o5ufU:10
Stack trace:
#0 /in/o5ufU(15): Foo->getTest()
#1 {main}
  thrown in /in/o5ufU on line 10

Process exited with code 255.

Patches

Pull Requests

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2018-01-16 15:43 UTC] nikic@php.net
-Status: Open +Status: Not a bug
 [2018-01-16 15:43 UTC] nikic@php.net
This behavior is intentional. A non-void return type requires an explicit return value. A void return type conversely prohibits an explicit return value (including "return null").
 [2018-01-16 15:52 UTC] adam at nostradamus dot nu
Hi Nikic, 

Accoording to this script, that's not entirely true: https://3v4l.org/hn6F0
 [2018-01-16 16:05 UTC] nikic@php.net
What is this script supposed to show? It does not use return types, and as such imposes no limitations on returns.
 [2018-01-16 16:08 UTC] adam at nostradamus dot nu
> What is this script supposed to show? It does not use return types, and as such imposes no limitations on returns.

That a void response is interpreted as null by php without a return type hint.
Isn't that a bit weird?
 [2018-01-16 16:26 UTC] nikic@php.net
As PHP does not have a materializable void type (in the sense of a type that a variable can have, not in the sense of a return type annotation), null is used as the next best approximation. (Even if you use an explicit ": void" annotation, you can still use the return value of the function, and that return value will be null.)
 
PHP Copyright © 2001-2025 The PHP Group
All rights reserved.
Last updated: Sat Jul 05 02:01:35 2025 UTC