« Back to Index

Basic Closure example in PHP

View original Gist on GitHub

Closure.php

<?php
    function doSomething($multiplier)
    {
        return array_map(function ($item) {
            return $item * $multiplier;
        }, array(1, 2, 3));
    }

    function doSomethingWithClosure($multiplier)
    {
        // We tell the Closure to `use` (i.e. pass through) `$multiplier` from the parent scope. 
        // If we didn't then `$multiplier` would be equal to zero (as scope within the anonymous function is lost).
        // The previous `doSomething` function demonstrates what would happen if we didn't pass through $multiplier. 
        return array_map(function ($item) use ($multiplier) {
            return $item * $multiplier;
        }, array(1, 2, 3));
    }

    print_r(doSomething(2)); // [0, 0, 0]
    print_r(doSomethingWithClosure(2));  // [2, 4, 6]