User Defined Function in PHP

Introduction

In this article I will explain User Defined Functions in PHP. A function is a block of statements used repeatedly in a program. A PHP function works as in other languages like "C". PHP provides one thousand built-in functions. These functions are defined as per our requirements, these functions are called User Defined Functions. A function is defined using the special keyword "function" and the function. A valid function name starts with a letter or underscore and function names are case-insensitive.

Syntax

function function name()

{

 Statements:

}

Example

<?php 

function f_name() 

echo "Good Bye.."

f_name(); 

?>

When we call the above function it will print "good bye".

Conditional Function

<?php

$name = true;

shyam();

if ($name) {

  function ram()

  {

    echo "I don't exist until program execution reaches me";

  }

}

if ($name) ram();

function shyam()

{

  echo "I exist immediately upon program start"."<br>";

}

?>

Output

UDF in PHP1.jpg

Functions within Functions

All functions and classes in PHP have a global scope. Functions and Classes can be called from outside of the program. Function overloading is not supported in PHP. It is not possible to undefine or redefine previously declared functions.

<?php

function ram()

{

  function shyam()

  {

    echo "I don't exist until ram() is called";

  }

}

ram();

shyam();

?>

Output
UDF in PHP2.jpg

Up Next
    Ebook Download
    View all
    Learn
    View all