<?php
// ############################ example 1 ###############################
// An arrow function example. A function that adds 1 to another integer
$function = fn(int $num) => 1 + $num;
echo $function(3) . PHP_EOL;
// ############################ example 2 ###############################
// Scope examples
class Bar
{
public function doBar()
{
echo sprintf('execute %s%s', __METHOD__, PHP_EOL);
}
}
class Foo
{
public function getFunction()
{
$bar = new Bar();
// Arrow function has access to $bar and $this, just like `function () use ($bar) {};`
return fn() => $bar->doBar();
}
}
$foo = new Foo();
$function = $foo->getFunction();
unset($foo);
// The instances previously in $bar and $foo still exists because of this arrow function.
$function();
// ############################ example 3 ###############################
class FooWithStatic
{
public function getFunction()
{
$bar = new Bar();
// Arrow function has access to $bar and $this, just like `function () use ($bar) {};`
return static fn() => $bar->doBar();
}
}
$fooWithStatic = new FooWithStatic();
$function = $fooWithStatic->getFunction();
unset($fooWithStatic);
// $this isn't in scope with the static arrow function, but $bar still exists.
// Be careful about objects that stay in memory because of how you use
// arrow functions.
$function();