Using Functions
Functions are used to perform a flourishing defined job that is usually repeated at changing places within a lattice site, interlacing application, or other software application. The overhaul sometimes needs persuaded counsel before performing its task, and sometimes returns a valuation to the calling folio or program.
An case history of how to utilize a clean advantage in PHP:
utility showMessage() {
echo "{$_SESSION["message"]}"; }
The above process shows a besides incomplex assistance that displays the paragraph of a session variable called 'message'. The doctrine vitality that while a user is using a mesh site, etc, legion messages are generated and stored in the 'message' session variable. Whenever the showMessage service is called, the words of the session variable are displayed. So, for example, when the user logs on, you could present a note saying that they hold done so. Likewise, when they log off, a contradistinctive sign could be displayed.
Calling a function
To ring the showMessage function, you would good necessitate to encompass the line:
showMessage()
in the lacework leaf (wrapped in php tags to distinguish it from normall HTML).
Passing values to a function
Often, a work requires one or besides input values in line to perform its task. For example, select the next paradigm that takes two numbers as input, and adds them together. The decision is then returned to the calling netting stage or program.
function addNumbers($number1,$number2) {
$answer = $number1 + $number2;
return $answer; }
In the calling programme we would hog something much the same to the following:
$number1 = "5";
$number2 = "6";
$sumOfNumbers = addNumbers($number1,$number2);
echo "$sumOfNumbers";
Obviously, in a positive program you would not retain the numbers hardcoded conforming this, on the contrary they would be obtained from user input or by some other means. Civility besides that although the appellation of the returned variable is $answer, the calling program makes no reference to that. We could, provided we wanted to, alter the calling program to:
$answer = addNumbers($number1,$number2);
echo "$answer";
which might assemble matters slightly easier to understand.
Published: February 25, 2008