Skip to content
Advertisement

How to fix? PHP variable not shows values inside function

I want to pass the variable in a function but get an error :

Working Example :

$text_line1 = function (TextToImage $handler) {
    $line_first ="Vasim";
    $handler->add($line_first)
            ->position(250, 100)
            ->font(24, __DIR__ . '/Roboto-Black.ttf')
            ->color(0, 0, 0);
};

Not Working :

$line_second = $imageMeta[2];
$text_line2 = function (TextToImage $handler) {

    $handler->add($line_second)
            ->position(250, 150)
            ->font(20, __DIR__ . '/Roboto-Black.ttf')
            ->color(0, 0, 0);
};

Advertisement

Answer

What you are looking for is the “USE” keyword (for anonymous functions, as you are using in your second example). This allows additional variables from the parent scope to be passed into the closure. Its usage can be a little tricky, see the official PHP anonymous function documentation for more information (specifically, see example #3).

$line_second = $imageMeta[2];
$text_line2 = function (TextToImage $handler) use ($line_second) {

    $handler->add($line_second)
            ->position(250, 150)
            ->font(20, __DIR__ . '/Roboto-Black.ttf')
            ->color(0, 0, 0);
};
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement