Changes

Jump to: navigation, search

PHP Functions

977 bytes added, 14:31, 10 August 2009
no edit summary
Parameters (or ''arguments'' as they are more frequently known) can be passed into a function. There are no significant restrictions of the number of arguments which can be passed through to the function.
A function can be designed to accept parameters by placing the parameter names inside the parentheses of the function definition. Those There are no specific rules on the names that can be given to these arguments other than those applying to variable names in general. In the following examples we will use $arg1 and $arg2 as argument variable names. These variables can then be accessed using the assigned names from within the function body as follows:
<pre>
<?php
function addNumbers ($val1arg1, $val2arg2)
{
return $val1 arg1 + $val2arg2;
}
?>
</pre>
In the above example the ''addNumbers()'' function accepts two parameters as argumentsassigned to variables ''arg1'' and ''arg2'' respectively, adds them together and returns the result.
== Calling PHP Functions ==
<pre>
<?php
function addNumbers ($val1arg1, $val2arg2)
{
return $val1 arg1 + $val2arg2;
}
<pre>
<?php
function addNumbers ($val1arg1, $val2arg2)
{
$val1 arg1 += 10; $val2 arg2 += 10; return $val1 arg1 + $val2arg2;
}
<pre>
<?php
function addNumbers (&$val1arg1, &$val2arg2)
{
$val1 arg1 += 10; $val2 arg2 += 10; return $val1 arg1 + $val2arg2;
}
<pre>
<?php
function &addNumbers ($val1arg1, $val2arg2)
{
$val1 arg1 += 10; $val2 varg2 += 10; return $val1 arg1 + $val2arg2;
}
?>
</pre>
 
Note that in the above example we have used variable names $arg1 and $arg2 for the function arguments and ''$var1'' and ''$var2'' for the script that calls the the function. It is also valid to use the same names for both the variables and the arguments. For example, the following is valid syntax:
 
<pre>
<?php
function addNumbers (&$var1, &$var2)
{
$var1 += 10;
$var2 += 10;
return $var1 + $var2;
}
 
$var1 = 10;
$var2 = 20;
 
echo "Before var1 = $var1, var2 = $var2 <br>";
addNumbers ($var1, $var2);
echo "After var1 = $var1, var2 = $var2 <br>";
?>
</pre>
 
The above re-use of variable names is possible because of something called ''variable scope''.
== Functions and Variable Scope ==

Navigation menu