Functions in PHP

Getting Started with PHP
Getting Started with PHP : Home
Introduction
Installation
Hello World
Data Types in PHP
Variables in PHP
Operators in PHP
Decision Making in PHP
Iterations in PHP
Functions in PHP
Arrays in PHP
Strings in PHP
Object Oriented PHP
Classes and Objects
Constructors
Inheritance
Object Interfaces
Static and Final
Advanced Features in PHP
GET and POST
Session in PHP
Cookies in PHP
Server Variables

Functions in PHP

User defined function
You can create function in PHP similar to C. The only difference here is that in C the function must be defined before it's called, there is no such requirement in PHP.But it has its limitation

  function test(arguments)
{
  statements
}

Those of you who are not familiar with arguments, passing arguments is a way of passing value to the function. These values are passed while calling the function. These is also a limitation with nested functions, the inner function can not be called unless you have called the outer function for at least once.

<?php
 function outer($val){
 	echo "Here is the value passed $val ";
 	function inner(){
 		echo "inner function";
 	}
 }
 $var = 2;
 outer($var); // $var is argument passed
 inner(); //inner function will only recognized after calling outer
?>


Output
Here is the value passed 2 inner function

If you try to call inner() before outer , it won't be recognized.
Also if you nest a function inside if statement, you can't call that function until the if expression is evaluated to be true.
Returning values
A function is terminated as soon as it returns some value. Values are returned using return statement. If there so no return statement stateent in the function it will return NULL. If a function has returend value and there are statements after return statement those won't be executed, the function is immediately terminated after it returns a value.

<?php
 function test(){
 	echo "function test \n"; // here no return statement
 }
 $test_return = test(); // we will store return value in variable
 $test_return = var_dump($test_return);
 echo "$test_return\n";

 function add($a,$b){
 	echo "function add\n";
 	return $a+$b;
 	echo "I am after return statement";
 }
 $add_return = add(2,3); // storing return value of add function
 $add_return = var_dump($add_return);
 echo "$add_return";

?>


Output
function test NULL function add int(5)

You can see that even though we gave no return statement, but it returned a value NULL. The statement after return statement is not executed(on line 12).
There are lots of in-built functions that are very useful and make things easier.

Login to Track Your Progress