CKTIS / PHP
Keyword fn
Create a Closure with a single expression whose value is returned.
Version: PHP 8.4; repository runtime, production runtime not attested
Syntax
fn(int $x): int => $x + $offsetCreate a Closure with a single expression whose value is returned. Variables used from the outer scope are captured automatically by value when the arrow function is created. Reassigning an outer scalar afterwards does not affect that captured value. In an instance method an ordinary arrow function binds $this, while static fn does not bind the object.
$offset=2; $add=fn(int $x):int=>$x+$offset; $offset=9;
echo json_encode([$add(3),$offset]);
class Binding {function test(){return [(fn()=>isset($this))(),(static fn()=>isset($this))()];}} echo "\n",json_encode((new Binding())->test());
[5,9]
[true,false]
Examples
<?php
$offset=2; $add=fn(int $x):int=>$x+$offset; $offset=9;
echo json_encode([$add(3),$offset]);
class Binding {function test(){return [(fn()=>isset($this))(),(static fn()=>isset($this))()];}} echo "\n",json_encode((new Binding())->test());
Result
[5,9] [true,false]