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)
(no subject)
no subject
(no subject)
(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)
(no subject)
(no subject)