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?

  • Cross-site duplicate - stackoverflow.com/questions/156767/…. – Eugene Podskal Sep 20 '14 at 17:16
  • That's not a duplicate. – Robert Harvey Sep 20 '14 at 17:18
  • Read evaluation strategy wikipage. – Basile Starynkevitch Sep 20 '14 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 '14 at 17:23
  • This might help. – Gaui Sep 20 '14 at 17:44
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
    It's more complicated than this, of course (this is "passing by value"), but you'll get to that. :) – Robert Harvey Sep 20 '14 at 17:34

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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