0
$inumber1 = 10;
$inumber2 = 20;

     function add($number1, $number2) {

        echo $number1 + $number2;
     }

     add($inumber1, $inumber2);

I'm learning PHP coding for the first time and I'm following tutorials online.

The tutorial fails to explain why the above works and adds the numbers even if the vars don't match what is used in the function. I did some trial and error and it seems that if they match when the function is called it will work. No matter what I name them like so.

$inumber1 = 10;
$inumber2 = 20;

 function add($sum1, $sum2) {

    echo $sum1 + $sum2;
 }

 add($inumber1, $inumber2);

How does the function know to add the above value's if they have different names, and how is this useful in programming PHP?

5
  • Cross-site duplicate - stackoverflow.com/questions/156767/…. Sep 20, 2014 at 17:16
  • That's not a duplicate. Sep 20, 2014 at 17:18
  • Read evaluation strategy wikipage. Sep 20, 2014 at 17:22
  • Yea I just read that whole page and still don't understand this. My guess is that calling the function with the var's that have the values you need they are then passed though the function structure. And can be named anything it just seems to be a layout of sorts. For the reason you can use the name constructed function with other var's that have different values but you dont need to write a whole new function. am i correct ?
    – John Floyd
    Sep 20, 2014 at 17:23
  • This might help.
    – Gaui
    Sep 20, 2014 at 17:44

1 Answer 1

3

When you write code like

$inumber1 = 10;
$inumber2 = 20;

 function add($sum1, $sum2) {

    echo $sum1 + $sum2;
 }

 add($inumber1, $inumber2);

What you are saying is "assign the value of $inumber1 to the function parameter $sum1." So now $sum1 contains the same value that $inumber1 does.

It's done this way so that you can pass any value or variable you want to the function.

The second example works exactly the same way. There's no name clash, because the formal parameter names take precedence over the names outside of the function.

$sum1 cannot be used outside the function.

1
  • 1
    It's more complicated than this, of course (this is "passing by value"), but you'll get to that. :) Sep 20, 2014 at 17:34

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.