Functions

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
impulse()
Forum Regular
Posts: 748
Joined: Wed Aug 09, 2006 8:36 am
Location: Staffordshire, UK
Contact:

Functions

Post 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?
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post 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.
User avatar
Chris Corbyn
Breakbeat Nuttzer
Posts: 13098
Joined: Wed Mar 24, 2004 7:57 am
Location: Melbourne, Australia

Post 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.
Post Reply