2016-11-24 74 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变量从当前范围截取。