We could create a new global variable. This is too damn ugly! We could rewrite or create a subclass of the Yii class. But this is just creating lots of work and possible future maintenance!

No, the answer is actually very simple. All we have to do is pass the additional values outside the anonymous scope with the use directive:

Here is an extract from a Yii2 GridView where I am declaring the action for the "Delete" button. Line 6 is where the ActionColumn will pass the $url, $model and $key variables to the callback function.


    [
        'class' => yii\grid\ActionColumn::class,
        'template' => '{delete}',
        'buttons' => [
            'delete' => function($url, $model, $key) {
                return Html::a(FAS::icon(FAS::_TRASH),
                    $url,
                    [
                        'data-action' => 'delete',
                        'data-confirm-string' => 'Are you sure you want to remove this User Group?',
                        'data-request' => $url,
                        'data-pjax-container' => '#user-group-assignment-grid',
                        'class' => 'user-group-assignment-action',
                    ]);
            },
        ],
    ],

Instead of setting the value of the 'data-pjax-container' within the callback function (line 13 above), We will initialise a variable with the value at the start of my script, use it elsewhere and also pass it to my callback function (see line 11 and 18 below)

// Set pjax container id
$pjaxContainer = 'user-group-assignment-grid';

    ...

    // Define ActionColumn within GridView
    [
        'class' => yii\grid\ActionColumn::class,
        'template' => '{delete}',
        'buttons' => [
            'delete' => function($url, $model, $key) use ($pjaxContainer) {
                return Html::a(FAS::icon(FAS::_TRASH),
                    $url,
                    [
                        'data-action' => 'delete',
                        'data-confirm-string' => 'Are you sure you want to remove this User Group?',
                        'data-request' => $url,
                        'data-pjax-container' => '#' . $pjaxContainer,
                        'class' => 'user-group-assignment-action',
                    ]);
            },
        ],
    ],

We could pass multiple values to a callback method and even pass a variable by reference:

            'delete' => function($url, $url, key) use ($selector, &$pjaxContainer) {

                ....

            },