2

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);
?>
Ruslan Osmanov
  • 20,486
  • 7
  • 46
  • 60
pi.314
  • 622
  • 5
  • 16

1 Answers1

2

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.

Ruslan Osmanov
  • 20,486
  • 7
  • 46
  • 60