php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Request #69571 type hinting not possible in use clause of closures
Submitted: 2015-05-04 15:07 UTC Modified: 2015-05-04 19:45 UTC
From: thomas+php at koch dot ro Assigned:
Status: Wont fix Package: *General Issues
PHP Version: 5.6.8 OS:
Private report: No CVE-ID: None
 [2015-05-04 15:07 UTC] thomas+php at koch dot ro
Description:
------------
I would have expected that I can use the same type hinting in the 'use' clause of a closure as in the parameter list. It's not a bug since it's not documented to be working but it's an issue in consistency.

Test script:
---------------
<?php
$a = function() use ( stdClass $b) { return 'hi';};
echo $a();

Expected result:
----------------
hi

Actual result:
--------------
Parse error:  syntax error, unexpected 'stdClass' (T_STRING), expecting '&' or variable (T_VARIABLE) in [...] on line 2

Patches

Pull Requests

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2015-05-04 19:45 UTC] requinix@php.net
-Status: Open +Status: Wont fix
 [2015-05-04 19:45 UTC] requinix@php.net
Type hinting doesn't make sense for a use clause. In there is supposed to be a list of variables that exist in the current scope that get copied into the closure*. As such the code should know the type (likely even the actual value) of each variable. Compare that with a parameter list where the function doesn't know what values someone may try to pass into it, thus typing becomes useful.

On that note, your example. It doesn't make sense either because $b does not exist, and if you run the code (without the stdClass hint) then you'll get a warning about that. If you then resolve the warning by defining $b then, well, you know exactly what $b is.

* References are a little different in that the function gets a copy of the reference, not of the underlying value. And like in other places, a by-ref variable doesn't have to exist at the time of the call.
 
PHP Copyright © 2001-2025 The PHP Group
All rights reserved.
Last updated: Fri Jul 04 14:01:35 2025 UTC