Callbacks and captures
Lesson 22 of 48 in Coddy's PHP for Java Developers course.
Java captures local variables only when final or effectively final; reassigning n after lambda creation would fail compilation. PHP arrows capture a current scalar value even if the outer variable is later reassigned. Shared object state can still mutate in either captured reference/identifier model.
A traditional PHP closure imports outer locals with use. use($x) captures its current value, while use(&$x) shares the variable. Arrow functions capture used outer variables by value automatically. Object handles inside a by-value capture can still refer to mutable objects; value capture is not deep cloning.
Java program
import java.util.*;
class Main {
public static void main(String[] args) throws Exception {
int n=2;java.util.function.IntSupplier f=()->n;System.out.println(f.getAsInt());
}
}Source output:
2PHP program
demo.php
<?php
declare(strict_types=1);
$n=2; $f=fn():int=>$n; $n=9; echo $f(),"\n";
PHP output:
2Challenge
EasyInput is [values,factor]. mapValues(array $values,callable $operation) calls the supplied operation once per value and returns a dense list in order. Driver supplies a multiplier. Do not assume all callers multiply.
The supplied main script reads one JSON value from standard input, checks the named public APIs, and prints the result. Implement the module declarations without printing; do not replace the launcher or read input from a module. Input satisfies the stated types and bounds.
Edit Functions.php. main.php is the locked entry file. Dependencies use require_once __DIR__ with a relative filename.
Try it yourself
<?php
declare(strict_types=1);
require_once __DIR__."/Functions.php";
function ensure(bool $ok,string $message):void{if(!$ok)throw new RuntimeException("API: ".$message);}
$input=json_decode(trim(stream_get_contents(STDIN)),true,512,JSON_THROW_ON_ERROR);
$seen=[];$f=function(int $n)use(&$seen):int{$seen[]=$n;return $n+7;};ensure(mapValues([2,5],$f)===[9,12] && $seen===[2,5],"supplied callback");
echo implode(",",mapValues($input[0],fn(int $x):int=>$x*$input[1])),"\n";
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in PHP for Java Developers
1Values and output
Modules and first runFormatting returned textAssignments and variablesDivision and conversionStrings and byte lengthsExplicit Boolean rulesRecap: receipt text4Functions and modules
Functions and return typesDefaults and named callsVariadic argumentsCallbacks and capturesrequire_once and scopeRecap: integer cents2Control flow
Branches and precedenceStrict match expressionsLoops and early exitsKeys and iterationRecap: shipping rules5Errors and boundaries
Exceptions and stateStrict input validationNull is not falsyRecap: validate a batchPractice on your own: Online PHP compiler