PHP Function Arguments


 

PHP Function Arguments

In this current tutorial we will come to know about various kinds of argument declaration in PHP function, what is the differences among those declarations etc. Examples will help you to illustrate the differences.

In this current tutorial we will come to know about various kinds of argument declaration in PHP function, what is the differences among those declarations etc. Examples will help you to illustrate the differences.

Arguments of User Defined PHP Functions:

In PHP we can pass the data to functions via the argument list by value, by reference, and default arguments.

These arguments are local to the function and after performing some calculation the function return control/value to the calling function.

In general we pass the arguments to the function by value, whenever we pass the values to other functions argument it becomes local to that function and whatever changes we made valid only within that function only, to make the change globally we should pass the data as reference. So, whatever change take place it will reflect to the calling portion of the program too.

We need to use '&' sign before the argument in the argument list of the function to declare the variable as reference of the variable.

PHP Function Arguments Example:

<?php

function add(){

return 12 +13;

}

echo "Addition of 12 and 13 is= ".add();

?> 

Output:

Addition of 12 and 13 is= 25

Example:

<?php

$a=14;

$b=34;

echo "Before calling the function:<br/>";

echo"\$a= ".$a." \$b= ".$b;

swap($a,$b);

echo "<br/>After calling the function:<br/>";

echo"\$a= ".$a." \$b= ".$b;

function swap(&$a,&$b){

$a+=$b;

$b=$a-$b;

$a-=$b;

}

?> 

Output:

Before calling the function:
$a= 14 $b= 34
After calling the function:
$a= 34 $b= 14

0

Example:

<?php

function add($a=20,$b=12)

1

{

return $a+$b;

}

2

echo add(1,1)."<br/>";

echo add()."<br/>";

echo add(null,null)."<br/>";

3

echo add(null,1)."<br/>";

echo add(11,null)."<br/>";

Output:

4 2
32
0
1
11

 

 

Ads