pi.314
pi.314

Reputation: 620

PHP GD creating image using a function

I don't understand why one of the lines is not being drawn in the following code:

<?php
    $canvas = imagecreatetruecolor(100, 100);

    $white = imagecolorallocate($canvas, 255, 255, 255);
    $black = imagecolorallocate($canvas, 0, 0, 0);

    imagefill($canvas,0,0,$black);

    function myLine()
    {
        imageline($canvas, 0,20,100,20,$white);
    }

    imageline($canvas, 0,60,100,60,$white); //this line is printed..
    myLine(); //but this line is not

    header('Content-Type: image/jpeg');
    imagejpeg($canvas);
    imagedestroy($canvas);
?>

Upvotes: 2

Views: 146

Answers (1)

Ruslan Osmanov
Ruslan Osmanov

Reputation: 21502

The reason is that you refer to $canvas and $white variables within the myLine function, and these variables are not available in the scope of this function. You should either pass them as arguments, or use global keyword.

Example

function myLine($canvas, $color) {
  imageline($canvas, 0,20,100,20, $color);
}

myLine($canvas, $white);

You can also use an anonymous function as follows:

$my_line = function() use ($canvas, $white) {
    imageline($canvas, 0,20,100,20, $white);
};

$my_line();

In this code, the $canvas and $white variables are taken from the current scope.

Upvotes: 2

Related Questions