Passing values to a function September 24, 2008
Posted by me2blog in Basic PHP programming, php.Tags: Passing values by reference, php, using default value while passing values to functions i
trackback
you can pass values to a function by adding the values between parantheses when u call the function but before that u should define the values while defining the function
While passing values, make sure of the following:
1. passing the right data type:
the value passed can be any data type, including arrays and objects. A good practice is to check the value type before using it. especailly when u r taking these values from the user.
To use built-in functions that check the type, see this previous post:
Changing the order of statement execution
2. passing values in the correct order:
when u call the function test($a,$b); using test($x,$y);
then $a = $x and $b = $y …. each variable will take a value in order, if u call test($y,$x);
then $a = $y and $b = $x ,,, which is not the same … so pay attention to the order!
3. passing the correct number of values:
If u pass less numbers of values then the PHP will assign the missing values to be NULL and u will have a warning message.
if u pass many values than the function expected, it will ignore the extra values!
Note: u can assign default value for ur variables, so in the case that u forget to pass some values, the function will user their defaults
function function_name($varibale1= “default value”, $variable2= “default value”)
{
block of statements
return;
}
4. Passing values by reference:
when u pass values into variables in the function definition, u pass them by value (by default), u can make as many changes as u want inside the function, but when u back from the function , the value will return to it’s previous value b4 calling the function bcz u send a copy from the variable. If u want ur changes to affect the variable pass that variable by reference (think about it as u pass a pointer) any changes inside the function will stay after exiting the function!
Passing by reference is used mainly when passing really large values bcz it’s much faster!
Example:
<?php
function welcome_by_name ($name= “Visitor”)
{
echo “Welcome “, $name;
return;
}
echo “Passing the name \”Noor\” to the welcome function<br> “;
welcome_by_name(“Noor”);
echo “<br> Using the default value while calling the function <br>”;
welcome_by_name();
?>
The output:
Passing the name “Noor” to the welcome function
WelcomeNoor
Using the default value while calling the function
Welcome Visitor

Comments»
No comments yet — be the first.