PHP Free Tutorial

Function in PHP

In PHP, Programming by Baqir Ali

What is a function?

Functions are self-contained units of a program designed to accomplish a specified task such as calculating a mortgage payment, retrieving data from a database, or checking for valid input.

Syntax:

function myfunct()  
{
     do this; do that;
     do this other thing;
}

When a function is called in a program, it is like taking a detour from the main part of the program.

Example 1:

PHP starts executing the instructions in the function, and when finished, returns to the main program and picks up where it left off. The following example first calls the functions and returns back then execute echo command to produce ‘The End…’

<?php
        display(10);
        echo "The End ...";
		function display()
		{
			echo "This is display Function <br>";
		}
?>

Output:

This is display Function
The End …

Example 2:

Functions can be used over and over again and thus save you from repetitious programming.

<?php
		for($i=1;$i<=3; $i++)
		{
			display();
		}
		// function definition
		function display()     //function signature
		{
			echo "Hello Functions";
			echo "<br>---------------------------------<br>";
		}
?>

Output:

Hello Functions
——————————————-
Hello Functions
——————————————-
Hello Functions
——————————————-

They are also used to break up a program into smaller modules to keep it better organized and easier to maintain.

Example 3:

By definition, a function is a block of statements that not only performs some task but can also return or receive a value.

Syntax: function receiving values

function addNums($param1, $param2, $param3)
{
     $sum = $param1 + $param2 + $param3; echo 'The sum is ' . $sum;
}
Syntax: function receiving and returning values
function addNums($param1, $param2, $param3)
{
     $sum = $param1 + $param2 + $param3; return $sum;
     return $sum;
}
<?php
		$result=calculate(5,10,5,2);
                echo "The result is ".$result;
		function calculate($a,$b,$c,$d)
		{
			return ( ( ($a+$b)-($c) )*$d);
		}
?>

Output:

The result is 20

Function Default Values in PHP

You can make function parameters optional by assigning default values to them as shown in the example below.

<html>
<head>
<title>Simple User-defined Function</title>
</head>

<body>
<?php
     function addNums($param1=0, $param2=0, $param3=0)
     {
          $sum = $param1 + $param2 + $param3; return $sum;
     }
     $Total = addNums(1,3);
     echo $Total;
?>
</body>
</html>

In this case, if you don’t pass a value into the function for one or more of the parameters, the default value of 0 will be used. When defining a function, all required parameters should precede optional parameters.

Variable Scope in PHP

In PHP, variables declared outside of functions are not available by default inside of functions. The following code illustrates this:

Local Variable in PHP

<html>
<head>
<title>Local Variables</title>
</head>
<body>
     <?php
         $a = 10;
         $b = 5;
         function incrNumBy()
         {
              $a += $b;
         }
         incrNumBy(); //results in two warnings as $a and $b are
          //undefined in the function scope echo $a; //outputs 10 to the 
          browser
     ?>
</body>
</html>

Global Variable in PHP

To make the variables available to the function, they must be declared within the function as global variables using the global keyword.

<html>
<head>
<title>Global Variables</title>
</head>
<body>
<?php
     $a = 10;
     $b = 5;
     function incrNumBy()
     {
          global $a,$b;
          $a += $b;
     }
     incrNumBy();
     echo $a; //outputs 15 to the browser
?>
</body>
</html>

By Reference vs. By Value in PHP

As a default, the variables are passed to functions by value,    meaning that the function’s receiving variables get copies of the values received rather than pointers to them. If the receiving variables are modified, the passed variables remain unaffected. The following code illustrates this.

<html>
<head>
<title>By Value</title>
</head>
<body>
<?php
     $a = 10;
     $b = 5;
     function incrNumBy($num,$incr)
     {
          $num += $incr;
     }
     incrNumBy($a,$b);
     echo $a; //outputs 10 to the browser
?>
</body>
</html>

The above code outputs “10” to the browser. Although $num was incremented by 5, $a was unaffected by the function call. To pass a variable by reference, put an ampersand (&) before the parameter in the function definition.

<html>
<head>
<title>By Reference</title>
</head>
<body>
<?php
     $a = 10;
     $b = 5;
     function incrNumBy(&$num,$incr)
     {
          $num += $incr;
     }
     incrNumBy($a,$b);
     echo $a; //outputs 15 to the browser
?>
</body>
</html>

This time the function outputs “15” because $num references the variable $ itself. So, any change in $num will affect $a.

Nested Function in PHP

PHP supports nesting functions. A nested function is defined and called from within another function. The outer function also called the parent function, has to be invoked for the nested function to become available to the program. Nested functions are rarely used. OuterFunction() must be called before NestedFunction() is available.

PHP functions can also be nested inside other statement blocks, such as conditional statements. As with nested functions, such functions will only be defined when that block of code has been executed.

<?php
function outer ($a, $b)
{
     print "Greetings from outer()\n<br />"; 
     function square($x)
     { // Nested function
          print "Greetings from square()\n<br/>";
          return $x * $x;
     }
     return square($a) + square($b);
}
$sum=outer(5,8); // Call to outer()
echo "The sum of the squares is: $sum\n<br";
$squared=square(5);
print "5 squared is: $squared.\n<br />";
?>

Output:

Greetings from outer()
Greetings from square()
Greetings from square()
The sum of the squares is: 89 5 squared is: 25.

The terms function and method are often used interchangeably. The term method refers to a function that is used with PHP objects.

Support us by sharing this post