Php Anonymous Function

Overview

In contrast to a named function like:

1<?php
2function multiply($x, $y)
3{
4	return $x * $y;
5}

An anonymous or unnamed-function, well has no name:

1<?php
2function ($x, $y) {
3	return $x * $y;
4}; //closing semicolon here is mandatory.

NOTE: semicolon after the closing curly bracket is mandatory as it is treated as an expression by php

Since it is unnamed, you need to store it's value in a variable and using the variable as function name:

1<?php
2// ...
3
4$multiply = function ($x, $y) {
5	return $x * $y;
6};
7
8echo $multiply(10, 20);  // call the anonymous function

Use of variables in parent scope

It cannot just use the parent scope variable, you need to include it via 'use':

1<?php
2
3$message = 'Hi';
4$say = function () use ($message) {
5	echo $message;
6};
7
8$say();

Note that the $message is passed to the anonymous function by value, not by reference.

To use the variable by reference, put '&' before each variable name to 'use':

 1<?php
 2
 3$message = 'Hi';
 4$say = function () use (&$message) {
 5	$message = 'Hello';
 6	echo $message;
 7};
 8
 9$say();
10echo $message;

NOTE: This is abridged from original https://www.phptutorial.net/php-tutorial/php-anonymous-functions/

See also https://ismael.casimpan.com/quicktasks/php-arrow-function/