PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Monday, October 10, 2022

[FIXED] How to use variable in closure functions in php?

 October 10, 2022     gd, intervention, laravel, laravel-5, php     No comments   

Issue

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');
                    });

Solution

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';
    });


Answered By - Ali
Answer Checked By - David Marino (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing