PHP Functions

tutorial and example
tutorial and example

PHP functions are used to reuse piece of code many times.  There are various built-in functions in PHP. A function will be executed by a call to the function.

Following are the advantage of PHP function.

  • Code Reusability
  • Less Code
  • Easy to understand

PHP User define Functions

PHP user-define functions are used to create own functions.  Let’s see how to declare user define function.

Syntax

functionfunctionName(){

//code to be executed;

}

Note: Function name must be start with a letter or underscore (not a number).

Example:

Output

Created User define function !

PHP function with Arguments

In PHP function, we can pass the information through arguments by comma. It supports Call by value, Call by Reference, Default argument values and variable –length argument list. 

Example 1

Output

Alok

John

Example2

Output

Your name:Alok Age20
Your name:John Age30

PHP Call By Reference

In PHPcall by reference, the function does not modify the actual value by default. But if we want to pass the value as a reference then it is possiblethrough ampersand ( &) symbol.

Example:

Output

Hello Call By Reference

PHP Call By Value

Call by value is used to pass the value directly to a function.  The called function uses the value in a local variable.  There is no affect the source variable when change it.

Example:

Output

70

40

PHP Default Argument Value Function

Sometime we do not want to pass any value to the function then it will use default arguments in function.

Example

Output

Hello John
Hello Ram
Hello Rohan