funeralcrasher: (Default)
$num = 10;
function multiply()
{
$num = $num * 10;
}
multiply();
echo $num;


This prints "10" to the screen.

$num = $num * 10;
echo $num;


But this prints "0".

Why is that?

Date: 2008-06-24 07:11 am (UTC)From: [identity profile] open-other-end.livejournal.com
$num = $num * 10 doesnt mean $num = 10. What's happening is you've set $num to 10, defined a function, ran a function that didn't actually affect $num, and then you've printed out $num again. Nothing's actually changed.

Is this Javascript? I don't know it too well, but I don't know how function declarations work. You need to say that $num is a parameter inside the function, and then return it back again. If you say instead something like

$num = 10
function multiply(var num)
{
$num = $num * 10;
return $num;
}
$num = multiply($num)
and then print out num, you should get 100.

Date: 2008-06-24 10:59 am (UTC)From: [identity profile] pkbarbiedoll.livejournal.com
Duh! I just saw that.. Because there isn't a global declaration in the function, the variable doesn't exist to the "outside world". I feel teh stoopid this am. lol.
thanks for the drawn out expl.

Profile

funeralcrasher: (Default)
funeralcrasher

June 2020

S M T W T F S
 123456
78910111213
141516 1718 1920
21222324252627
282930    

Most Popular Tags

Style Credit

Expand Cut Tags

No cut tags
Page generated Jul. 1st, 2025 07:27 am
Powered by Dreamwidth Studios