Back to home

Simple Example
PHP Anonymous Functions main image

PHP Anonymous Functions

The basic gist is to use the keyword function() with a block scope.

If you want to use variables declared by the direct parent scope, ensure you use the use() keyword. A simple example of this can be found below.

Simple Example

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 // anon.php <?php function helloWorld() { $anon = function() { return 'Hello, World!'; }; return $anon(); } function sumTwoArgsPlusOne($a, $b) { $c = 1; $anon = function($a, $b) use ($c) { return $a + $b + $c; }; return $anon($a, $b); }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 // anon_test.php <?php require "anonymous.php"; class AnonymousTest extends PHPUnit\Framework\TestCase { public function testHelloWorld() { $this->assertEquals('Hello, World!', helloWorld()); } public function testSum() { $this->assertEquals(4, sumTwoArgsPlusOne(1, 2)); } }

Dennis O'Keeffe

@dennisokeeffe92
  • Melbourne, Australia

Hi, I am a professional Software Engineer. Formerly of Culture Amp, UsabilityHub, Present Company and NightGuru.
I am currently working on workingoutloud.dev, Den Dribbles and LandPad .

Related articles


1,200+ PEOPLE ALREADY JOINED ❤️️

Get fresh posts + news direct to your inbox.

No spam. We only send you relevant content.