Anitha Iyer Anitha Iyer - 7 months ago 24
PHP Question

How to use variable in closure functions in php?

I am using intervention for php for image manipulations.
Is it possible to apply font size and color to text through a variable like this?
I have calculated $fontsize and $color above this but it says undefined variable

$img->text($string, $item['x'], $top, function($font) {
$font->file('assets/fonts/Roboto-Medium.ttf');
$font->size($fontsize);
$font->color($color);
$font->align('left');
$font->valign('top');
});

Ali Ali
Answer

You need to use below syntax to pass variable:
Here you need to use a use() method.

$img->text($string, $item['x'], $top, function() use($font){
    $font->file('assets/fonts/Roboto-Medium.ttf');
    $font->size($fontsize);
    $font->color($color);
    $font->align('left');
    $font->valign('top');
});

EDIT

Here $font must be a Class object as this is used in the callback function. If you just want array then go for the following way:

$font = []; // initialize array
$img->text($string, $item['x'], $top, function() use($font){
        $font['file'] = 'assets/fonts/Roboto-Medium.ttf';
        $font['size'] = $fontsize;
        $font['color'] = $color;
        $font['align'] = 'left';
        $font['valign'] = 'top';
    });
Comments