Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Function with return type and "use" keyword

Tags:

php-7

How can you create a function that specifies both the return type and the external variables to use?

Are the examples below wrong or is it not supported (yet)?

<?php

$arr = ['test' => 'value'];

function test1() use ($arr) : string { // Line 5
    return $arr['test'];
}
function test2() : string use ($arr) {
    return $arr['test'];
}

The error is:

Parse error: syntax error, unexpected 'use' (T_USE), expecting '{' in [PATH]\index.php on line 5

You can run the code here.

like image 834
Sverri M. Olsen Avatar asked Sep 17 '25 14:09

Sverri M. Olsen


1 Answers

As answered by Adam Cameron in the comments, the problem is that the use language construct only applies to closures, not to all functions. Thus, using it on normal functions makes no sense and is as such not understood by the parser.

When the function in the example code would have been a closure, everything would have worked.

$arr = ['test' => 'value'];

$fn = function() use ($arr) : string {
    return $arr['test'];
};

echo($fn()); // outputs 'value'

You can run the code here.

Note that your first attempt is correct: first the use statement, then the return type declaration. Trying to reverse these two will result in a parse error.

like image 166
Just a student Avatar answered Sep 19 '25 06:09

Just a student