funeralcrasher (
funeralcrasher) wrote2008-06-23 10:33 am
![[personal profile]](https://www.dreamwidth.org/img/silk/identity/user.png)
Stumped.
$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?
$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?
no subject
Try:
$num = 10;
$num = $num * 10;
echo $num;
no subject
Why does the function print 10?
no subject
no subject
no subject
The problem remains, though - if $x * 2 = 0 (where x is not set), then why is the function returning a number instead of 0?
no subject
no subject
The problem is that $num inside multiply() is not the same $num you set to 10. It is a new $num, local to that function.
If you want that function to work you either have to pass the value and return it, or reference the global variable.
// Pass example:
$num = 10;
function multiply($num)
{
$num = ($num * 10);
return $num;
}
$num = multiply($num);
echo $num;
// Global reference example:
$num = 10;
function multiply()
{
global $num;
$num = ($num * 10);
}
multiply();
echo $num;
Required reading: http://us3.php.net/variables.scope
no subject
What I don't understand is why $num = $num * 10; equals 10, when $num is undefined (ie, 0 right?)
no subject
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.
no subject
thanks for the drawn out expl.