2016-11-24 36 views
2

我不明白,爲什麼線之一不被下面的代碼繪製創建的圖像:PHP GD使用功能

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

回答

2

的原因是,你是指$canvas$white變量myLine內函數,並且這些變量在此函數的scope中不可用。您應該將它們作爲參數傳遞,或使用global keyword

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

myLine($canvas, $white); 

也可以使用一個anonymous function如下:

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

$my_line(); 

在該代碼中,$canvas$white變量從當前範圍截取。