PDA

Click to See Complete Forum and Search --> : [RESOLVED] it doesn't work in function


wiz126
Feb 6th, 2007, 03:55 PM
ok My code doesn't work when its in a function, yet it does when its not why is that?

This Works:

$handle = fopen("http://www.runescape.com/lang/en/aff/runescape/serverlist.ws?lores.x=0&plugin=0&order=WPML","r");
if($handle){
while (!feof($handle)) {
$contents .= fread($handle,8192);}
fclose($handle);}

$world = 2;
$lengthA = strpos(stristr($contents, 'World '.$world), 'FULL');
$lengthB = strpos(stristr($contents, 'World '.$world), 'Players');

if ($lengthA < $lengthB){
echo 'Full';
}
else
{
echo strpos(stristr($contents, 'World '.$world), 'Players');
}

And This Doesn't:

$handle = fopen("http://www.runescape.com/lang/en/aff/runescape/serverlist.ws?lores.x=0&plugin=0&order=WPML","r");
if($handle){
while (!feof($handle)) {
$contents .= fread($handle,8192);}
fclose($handle);}


function Population($world) {
$lengthA = strpos(stristr($contents, 'World '.$world), 'FULL');
$lengthB = strpos(stristr($contents, 'World '.$world), 'Players');

if ($lengthA < $lengthB){
return "Full";
}
else
{
return strpos(stristr($contents, 'World '.$world), 'Players');
}
}
echo Population(2);

Why is that?

visualAd
Feb 6th, 2007, 04:15 PM
Its because of variable scope ($handle is used outside the function). Any variable initialised outside a function must be accessed via the $GLOBALS array or declared in the function using global:

$handle = ....

function blah()
{
echo($GLOBALS['handle']);
}

function glah()
{
global $handle;

echo($handle);
}

wiz126
Feb 6th, 2007, 04:46 PM
WOW I am dumb! I forgat the global $contents; I have waisted a whole 30 minuts on that crap! and all the problem was a line i forgat.... thank man