I wrote a function that is supposed to take some variables and then change the value of those variables. However, after running the function, the variables remained unchanged. Then I did some googling and discovered you need to put an &
in front of variable names. The code then did what I wanted it to do. However, I don't understand why you would need to put an &
. Is there some other way to accomplish what I needed to do? Basically I'm confused with the notion of passing by reference. This is where my woes start, LOL:
In all the languages I’ve learned so far (python, java, ruby), the parameters that a function would take would change the value of the variables as instructed in the algorithm without any passing by reference
, a concept that I've just discovered in PHP. Why has PHP chosen to do this? Could you please explain the logic behind references? Finally, there's people all over the web who are saying: Don't use references? If not, how else do I get to my solution. Then there's also deprecations in for references in PHP... Sorry it's a jumble.
I went through the PHP Manual for references but I found it pretty hard to digest.
Here's some code that I added the &
sign to:
<?php
$comments = "";
$airline_name = "United";
$flight_number = "262";
$departure_airport = "";
function airport(&$one, &$two, &$three, &$four) {
if ( !empty($one) || !empty($two) || !empty($three) ) {
$one = !empty($one) ? "Airline Name: $one<br>" :"Airline Name: PLEASE PROVIDE AIRLINE NAME<br>";
$two = !empty($two) ? "Flight Number: $two<br>" : "Flight Number: PLEASE PROVIDE FLIGHT NUMBER<br>";
$three = !empty($three) ? "Departure Airport: $three<br>" : "Departure Airport: PLEASE PROVIDE DEPARTURE AIRPORT<br>";
$four = !empty($four) ? "Comments: $four<br>" : "";
}
}
airport($airline_name,$flight_number,$departure_airport,$comments);
echo $airline_name,$flight_number,$departure_airport,$comments;
?>