Executing encapsulated PHP code with a closure

Published on 2023-09-30 • Modified on 2023-09-30

This snippet shows how to execute encapsulated PHP code with a closure. Sometimes, one needs to run some code encapsulated by some other code, like common tasks that must be run before and after. We can use a closure to achieve this. In the following example, whatever the code we pass to the snippet267UseClosureAsArgument function, it first displays "before", then the code we passed is executed, and finally "after" is displayed.


<?php

declare(strict_types=1);

namespace App\Controller\Snippet;

/**
 * I am using a PHP trait to isolate each snippet in a file.
 * This code should be called from a Symfony controller extending AbstractController (as of Symfony 4.2)
 * or Symfony\Bundle\FrameworkBundle\Controller\Controller (Symfony <= 4.1).
 * Services are injected in the main controller constructor.
 */
trait Snippet276Trait
{
    public function snippet276(): void
    {
        $this->snippet267UseClosureAsArgument(function () {
            echo 'With an anonymous function';
        });

        $closure = function () {
            echo 'With a closure assigned to a variable';
        };
        $this->snippet267UseClosureAsArgument($closure);

        $this->snippet267UseClosureAsArgument(fn () => print ('With an arrow function'));

        // That's it! 😁
    }

    public function snippet267UseClosureAsArgument(\Closure $closure): void
    {
        echo 'before'.PHP_EOL;
        $closure();
        echo PHP_EOL.'after';
        echo PHP_EOL.PHP_EOL;
    }
}

 Run this snippet  More on Stackoverflow   Read the doc  More on the web  Random snippet

  Work with me!