views:

38

answers:

3

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)

or

(int)$hrs * (float)$zoom

but no success :(

Any help would be appreciated.

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

include('header.php')

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

+1  A: 

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;
}
middaparka
For some reason that didn't work when I tried it before?
ajo
@user381636 Most likely a typo or summat. :-)
middaparka
A: 
$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

VolkerK
A: 

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;
}
Matt Williamson
Use of globals really isn't ideal (especially if there's no need for it).
middaparka
Agreed. Edit above.
Matt Williamson
Thanks. So simple ...
ajo