PHP Function

PHP

In this tutorial we will learn about functions in PHP.

What is a function?

A function is a self contained block of code that is written to do a specific task.

Following are some of the reasons why we use functions.

  • Break a project into smaller parts.
  • To reduce duplicating code.
  • Focus on a specific task.
  • Helps in quick error fixing as a function is supposed to perform specific task.

Calling functions

We call a function by writing its name followed by open-close parentheses and then a semicolon.

greetings();	//calling a greetings function

Creating function in PHP

To create a function in PHP we use the function keyword followed by the function name and then open-close parentheses. In the following example we have created a greetings function which when called will print "Hello".

function greetings() {
	printf("Hello");
}

greetings();	//calling function

We can also pass arguments to a function. In the following example the function greeting can take an argument called $name and will print a greeting message when value is passed.

function greetings($name) {
	printf("Hello %s", $name);
}

greetings("Yusuf");	//calling function

Difference between function argument and function parameter

The value we pass to a function is called the agrument of the function and the actual variable that receives the argument is called the function parameter. But in practice, developers use these two terms interchangeably.

function greetings($name) {	//variable $name is the parameter
	printf("Hello %s", $name);
}

//calling function
greetings("Yusuf");	//value "Yusuf" is the argument

In the above example the variable $name in the function greetings is the parameter and the value "Yusuf" passed when calling it is the argument.

Function parameters

The variable of a function that is going to receive argument value is called the function parameter. The parameter can have default values too.

In the following example we have a function parameter with default value.

function greetings($text = "World") {	//default value
	printf("Hello %s", $text);
}

//calling function
greetings();		//no argument passed, Output: "Hello World"

//calling function
greetings("Yusuf");	//argument passed, Output: "Hello Yusuf"

In the above code the function parameter $text is assigned a default value "World". When argument is not passed when greetings function is called then "Hello World" is printed. And when we pass an argument "Yusuf" then that value is assigned to $text variable and we get "Hello Yusuf" as output.

Function returning value

We use the return keyword to return value from a function.

In the following function we are returning a string which is then printed.

function greetings($text = "World") {

	return sprintf("Hello %s", $text);	//returning string

}

$message = greetings("Yusuf");	//calling function

printf($message);	//printing output

The above code will print "Hello Yusuf".

Function returning multiple values

We can return multiple values from a function by using array.

function add_sub($x, $y) {
	$add = $x + $y;
	$sub = $x - $y;

	return array($add, $sub);
}

list($add_ans, $sub_ans) = add_sub(10, 20);

printf("Add = %d, Sub = %d", $add_ans, $sub_ans);

Output of the above code:
Add = 30, Sub = -10

Local variable and its scope

A variable created inside a function is called a local variable and it is only accessible inside that function and exists only inside that function. When we go out of that function the local variable is not accessible.

function greetings() {

	//this is a local variable and only accessible inside this function
	$text = "Hello";

	printf($text);	//this will print "Hello"

}

$text = "Hi";

greetings();

printf($text);		//this will print "Hi"

Global variable and its scope

A variable created outside of all the functions is called a global variable and it is accessible even inside a function.

To access a global variable inside a function we use the global keyword.

//global variable
$text = "Hi";

function greetings() {
	
	//local variable
	$text = "Hello";

	printf($text);	//print "Hello"

	global $text;	//global variable

	printf($text);	//print "Hi"

}

greetings();	//function call

printf($text);	//print "Hi"

Static variable and its scope

We use static keyword to create a static variable. A static variable remembers its value even after we exit the function.

First lets talk about non-static example.

function disp() {
	
	$i = 0;	//non-static variable

	printf($i);

	$i++;

}

disp();	//output 0
disp();	//output 0
disp();	//output 0

In the above code we have a non-static variable $i. When we call the disp() function the variable $i is set to 0. And then we print the value of $i and finally we increment it by 1 using increment operator and then we exit the function.

Since $i is a non-static variable so, each time we call disp() function $i is set to 0 and hence each time we get the output 0.

Now, lets look at the static variable example which remembers its value even after we exit the function.

function disp() {
	
	static $i = 0;	//static variable

	printf($i);

	$i++;

}

disp();	//output 0
disp();	//output 1
disp();	//output 2

In the above code we have a static variable $i. When we call the disp() function for the first time the variable $i is set to 0. And then we print the value of $i and finally we increment it by 1 using increment operator and we exit the function.

Since $i is a static variable so, it remembers its last value i.e, 1 from the first call. So, when the second call is made to disp() function, $i is not set to 0 again rather it uses its earlier value 1. Hence, we have output 0 1 and 2.

Call by Value

In PHP we can pass value to a function and the function can return back some value using the return statement. This is actually done in PHP by passing a copy of the actual value and any change made to that copy inside the function has no effect on the actual value.

//value is passed
function change_value($i) {
	
	$i = $i + 10;	//add 10 to the value

	printf($i);		//print new value of i

}

$i = 5;				//actual value

printf($i);			//original value of i printed

change_value($i);	//calling function, copy of i is passed, original value unchanged

printf($i);			//original value of i printed

Call by Reference

In some scenarios we want to work with the actual value rather than a copy for this PHP provides us with call by reference concept. In this case the reference to tha actual value is passed and any change made inside a function is reflected back.

//reference is passed, variable x refers i in this example
function change_value( &$x ) {
	
	$x = $x + 10;	//add 10 to x, this is reflected back to original variable

	printf($x);		//print the new value of x

}

$i = 5;		//actual value

printf($i);	//original value of i printed

change_value($i);	//calling function, original value of $i is now changed.

printf($i);	//new value of i printed

By adding the & symbol to the parameter $x in the function we are saying that the argument passed to the function change_value() is a reference and not a copy. So, any change made inside the function to the variable $x (which refers i) is reflected back to variable i.

Function returning reference

We can also make a function in PHP return reference to a variable instead of the value by placing the & symbol before the function name.

//variable X
$X = 10;

function &refX () {
	
	global $X;

	return $X;

}

//variable i will now refer to variable X
//as the function refX returns reference.
$i =& refX();

printf($i);		//this will print 10, which is also the value of X

//now change value of X
$X = 20;


//since value of X changed so it will be reflected
//back to variable i as i is referencing X

printf($i);		//this will print 20, the new value of X

The recursive function

In simple terms, when a function calls itself then it is a recursive function.

One the famous example is printing factorial of n using recursive function.

In maths, a factorial of a non-negative number n is the product of all the positive integers less than or equal to n. Factorial is denoted by n!

Example: Factorial of 5 is = 5!
5! = 5x4x3x2x1
= 120

function fact($n) {
	
	if ($n == 0) {
		return 1;
	}

	return $n * fact($n - 1);

}

printf("Factorial of 5 = %d", fact(5));

The above code will print "Factorial of 5 = 120".