Back to questions
JuniorTheoryCommon
What happens when you run this program?
<?php
$rate = 2;
function apply($x)
{
return $x * $rate;
}
echo apply(10), "\n";A Warning: Undefined variable $rate, then 0
- Expecting
20, as in JavaScript: a PHP function does not see the variables of the file around it, so$ratehas to come in as a parameter. - Expecting an undefined variable to stop the program: it is only a Warning, PHP uses
nullin its place, and10 * nullgives0.
- How would you change
applyso that it uses the file's$ratecorrectly? - What does
global $rate;do inside the function, and why is it avoided?