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);
?>

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.