Pass by reference to modify a variable from within an inner closure

This is part of the Semicolon&Sons Code Diary - consisting of lessons learned on the job. You're in the PHP category.

Last Updated: 2021-05-16

I could not get this variable $smsCounter to increment inside this PHP closure:

<?php

$smsCounter = 0;
Bus::assertDispatched(function (SendSms $job) use ($smsCounter) {
    $smsCounter = $smsCounter + 1;
    return true;
});
$this->assertEquals($smsCounter, 1);

The trick was to pass by reference instead. This enables the inner closure to modify the outer. Note the use of an ampersand (&) before the variable name below:

<?php
  Bus::assertDispatched(function (SendSms $job) use (&$smsCounter) {
    ...
  });
  ...