Alexandre Khoury
Alexandre Khoury

Reputation: 4022

Difference if the code is in a function

I have this code:

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

At first glance, we would think that it will output the same result twice.

But the output is:

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

How could it be?
What must I do to put the code in a function and to make it work?

Upvotes: 0

Views: 66

Answers (4)

hectorct
hectorct

Reputation: 3555

$img is not visible inside the function. You must use the keyword global inside the function to make it visible.

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

See php.net/manual/language.variables.scope.php

Upvotes: 1

deceze
deceze

Reputation: 522499

Variables have function scope. $img is not defined and not available inside your foo function. You need to pass it into the function as well.

Upvotes: 0

user1202278
user1202278

Reputation: 773

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

It's Unable to access that variable defined outside the function.

Upvotes: 0

Lo&#239;c Faure-Lacroix
Lo&#239;c Faure-Lacroix

Reputation: 13600

did you try passing the $img as argument?

Or if you really insist not passing $img as argument. You could also put that at the top of your function.

global $img;

As someone said it this question. $img wasn't defined in the function scope. To access it, you either have to use global if its a global variable. Or you have to pass it as a parameter.

Upvotes: 1

Related Questions