如果代码在函数中则不同

时间:2012-07-08 09:47:29

标签: php

我有这段代码:

$img=imagecreatefrompng('http://partner-ad.photobucket.com/albums/g46/xanatha/WidgieWorld/Small-Yellow-Ball.png');

function foo($x,$y)
{
    $col=imagecolorat($img,$x,$y);
    $col=imagecolorsforindex($img,$col);
    var_dump($col);
}
foo(0,0);

echo '<br />';

$col=imagecolorat($img,0,0);
$col=imagecolorsforindex($img,$col);
var_dump($col);

乍一看,我们认为它会输出两次相同的结果。

但输出是:

NULL
array(4) { ["red"]=> int(255) ["green"]=> int(255) ["blue"]=> int(255) ["alpha"]=> int(0) } 

怎么可能? 我该怎么做才能将代码放在一个函数中并使其工作?

4 个答案:

答案 0 :(得分:2)

您是否尝试将$img作为参数传递?

或者,如果你真的坚持不传递$img作为参数。您也可以将它放在函数的顶部。

global $img;

有人说这个问题。函数范围中未定义$img。要访问它,如果它是一个全局变量,则必须使用global。或者您必须将其作为参数传递。

答案 1 :(得分:1)

$img在函数内部不可见。您必须在函数内使用关键字global才能使其可见。

$img=imagecreatefrompng('http://partner-ad.photobucket.com/albums/g46/xanatha/WidgieWorld/Small-Yellow-Ball.png');

function foo($x,$y)
{
    global $img; //<--------------Makes $img visible inside the function
    $col=imagecolorat($img,$x,$y);
    $col=imagecolorsforindex($img,$col);
    var_dump($col);
}
foo(0,0);

echo '<br />';

$col=imagecolorat($img,0,0);
$col=imagecolorsforindex($img,$col);
var_dump($col);

请参阅php.net/manual/language.variables.scope.php

答案 2 :(得分:0)

function foo($x,$y,$img)
{
    $img_png = imagecreatefrompng($img);
    $col=imagecolorat($img_png,$x,$y);
    $col=imagecolorsforindex($img_png,$col);
    var_dump($col);
}
foo(0,0,'http://partner-ad.photobucket.com/albums/g46/xanatha/WidgieWorld/Small-Yellow-Ball.png');

无法访问函数外部定义的变量。

答案 3 :(得分:0)

变量具有功能范围$img功能中未foo未定义且无法使用。您还需要将其传递给函数。