$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
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