Page 1 of 1

Functions

Posted: Sat Sep 23, 2006 9:59 am
by impulse()
If I create a function, for example

Code: Select all

function add($numOne, $numTwo) {
  $val = $numOne + $numTwo; }
In the parameter list, that's in brackets, why are those there? If they weren't there wouldn't the variables be passed in from outside of the function anyway?

Posted: Sat Sep 23, 2006 10:16 am
by feyd
Sure, they'd be passed in since PHP functions use variable length arguments, but you wouldn't be able to use $numOne or $numTwo out of the box.

Posted: Sat Sep 23, 2006 11:11 am
by Chris Corbyn
Are you confusing global scoped variables with local-scoped variables?

The names in the function declaration are the names used locally inside the function. If they were defined globally (outside the function) they would need to be declared global inside the function.

Code: Select all

function add($num1, $num2)
{
    return $num1 + $num2;
}

echo add(10, 2); //12

Code: Select all

$num1 = 10;
$num2 = 2;

function add()
{
    global $num1, $num2;
    return $num1 + $num2;
}

echo add(); //12 (yuck! - don't do this!)
Anything passed in as an argument will be assigned to that local variable in the first example so you know what's going on regardless of the environment around the function.