Tutorial :PHP function call not working - presumed casting problem?


Why does THIS not work when called via e.g. wd(1) (it always returns '-2')?

$zoom=$user['zoom'];  function wd($hrs){    return $hrs*$zoom-2;  }  

But THIS works fine:

function wd($hrs){    return $hrs*30-2;  }  

Assuming this was a casting problem, I tried all sorts of variations like

(int)$hrs * ((int)$zoom)  


(int)$hrs * (float)$zoom  

but no success :(

Any help would be appreciated.

(And BTW, does it matter whether the function is located within


-- although I tried it both within and outside the header?)


EDIT: You should pass that variable as an argument to the function, but if you absolutely need to keep the variable global, do the following.

You need to bring the global into scope:

$zoom=$user['zoom'];  function wd($hrs){    global $zoom;    return $hrs*$zoom-2;  }  


This isn't a casting issue - it's because you're trying to use a variable that's out of scope.

Whilst you'll need to read the PHP docs for the full low-down, at a basic level, you can only access variables that are defined within the same function or method. (Although you can use the global keyword to access global variables. That said, global variables are less than ideal.)

As such, you could simply update your function to also pass in 'zoom' as a parameter as follows:

function wd($hrs, $zoom){    return $hrs*$zoom-2;  }  


$zoom=$user['zoom'];  function wd($hrs){    // there is no variable $zoom within the function's visibility scope    // so you will get a "Notice: undefined variable 'zoom'" here.    return $hrs*$zoom-2;  }  

see http://docs.php.net/language.variables.scope

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Next Post »