PHP User Defined Functions

User Defined Functions

Besides the built-in PHP functions, we can create our own functions.
A function is a block of statements that can be used repeatedly in a program.
A function will not execute immediately when a page loads.
A function will be executed by a call to the function.

Defining a user defined function

A user defined function declaration starts with the word function:
A function name can start with a letter or underscore (not a number).
Give the function a name that reflects what the function does!

Syntax:

function functionName() {
    //statements;
}
Note:

Function names are case-insensitive, though it is usually good form to call functions as they appear in their declaration.

Calling Function

A function can be called with it's name followed by ( ).

Syntax:

A user defined function can call as follows:

functionName();  // calling function

Example:

This example defines a function named printMsg witch prints a message "Hello World!".
In 5th line printMsg(); is call the function defined above.

<?php
    function printMsg() {
        echo "Hello World!";
    }
    printMsg(); // call the function
?>

Output:

Tutorialik.com
Hello World!

Returning values from function

To let a function return a value, use the return statement:

Syntax:

function functionName() {
    //statements;
    return;
}

Example:

This example defines a function named add having two argument $a and $b, witch is initializes with value given from function call ($a = 5, $b = 7).
The statement $c = $a + $b; Inside body of the function performs addition of $a and $b and final value is assign to $c.
Last line of function returns value of $c, which is returned to were function is called, and assigns the value to $ans.
Finally we get the answer and we print it using echo statement.

<?php
    function add($a, $b) {
        $c = $a + $b;
        return $c;
    }

    $ans = add(5, 7); // call the function
    echo "Addition of 5 + 7 = $ans";
?>

Output:

Tutorialik.com
Addition of 5 + 7 = 12

Share This Page to Download:

Share to Download

Share This Page on:


Ask Question