Javascript: Functions

 

PHP Functions


PHP function is a piece of code that can be reused many times. It can take input as argument list and return value. There are thousands of built-in functions in PHP.

Advantage of PHP Functions

Code Reusability: PHP functions are defined only once and can be invoked many times, like in other programming languages.

PHP User-defined Functions

We can declare and call user-defined functions easily. Let’s see the syntax to declare user-defined functions.

Syntax

  1. function functionname(){
  2. //code to be executed
  3. }

 

PHP Functions Example

File: function1.php

  1. function sayHello(){
  2. echo “Hello PHP Function”;
  3. }
  4. sayHello();//calling function
  5. ?>

Output:

Hello PHP Function

PHP Function Arguments

We can pass the information in PHP function through arguments which is separated by comma.

PHP supports Call by Value (default), Call by Reference, Default argument values and Variable-length argument list.

Let’s see the example to pass single argument in PHP function.

File: functionarg.php

  1. function sayHello($name){
  2. echo “Hello $name
    ;
  3. }
  4. sayHello(“Sonoo”);
  5. sayHello(“Vimal”);
  6. sayHello(“John”);
  7. ?>

Output:

Hello Sonoo
Hello Vimal
Hello John

PHP Call By Reference

Value passed to the function doesn’t modify the actual value by default (call by value). But we can do so by passing value as a reference.

By default, value passed to the function is call by value. To pass value as a reference, you need to use ampersand (&) symbol before the argument name.

Let’s see a simple example of call by reference in PHP.

File: functionref.php

  1. function adder(&$str2)
  2. {
  3.     $str2 .= ‘Call By Reference’;
  4. }
  5. $str = ‘Hello ‘;
  6. adder($str);
  7. echo $str;
  8. ?>

Output:

Hello Call By Reference