
- PHP 7 Tutorial
- PHP 7 - Home
- PHP 7 - Introduction
- PHP 7 - Performance
- PHP 7 - Environment Setup
- PHP 7 - Scalar Type Declarations
- PHP 7 - Return Type Declarations
- PHP 7 - Null Coalescing Operator
- PHP 7 - Spaceship Operator
- PHP 7 - Constant Arrays
- PHP 7 - Anonymous Classes
- PHP 7 - Closure::call()
- PHP 7 - Filtered unserialize()
- PHP 7 - IntlChar
- PHP 7 - CSPRNG
- PHP 7 - Expectations
- PHP 7 - use Statement
- PHP 7 - Error Handling
- PHP 7 - Integer Division
- PHP 7 - Session Options
- PHP 7 - Deprecated Features
- PHP 7 - Removed Extensions & SAPIs
- PHP 7 Useful Resources
- PHP 7 - Quick Guide
- PHP 7 - Useful Resources
- PHP 7 - Discussion
PHP User-defined functions
Introduction
PHP has a large number of built-in functions such as mathematical, string, date, array functions etc. It is also possible to define a function as per specific requirement. Such function is called user defined function.
A function is a reusable block of statements that performs a specific task. This block is defined with function keyword and is given a name that starts with an alphabet or underscore. This function may be called from anywhere within the program any number of times.
Syntax
//define a function function myfunction($arg1, $arg2, ... $argn) { statement1; statement2; .. .. return $val; } //call function $ret=myfunction($arg1, $arg2, ... $argn);
Function may be defined with optional but any number of arguments. However, same number of arguments must be provided while calling. Function's body can contain any valid PHP code i.e. conditionals, loops etc. (even other functions or classes may be defined inside a function). After executing statements in the block, program control goes back to the location from which it was invoked irrespective of presence of last statement of function block as return. An expression in front of return statement returns its value to calling environment.
user defined function Example
In following example shows definition and call to a usr defined function sayhello()
Example
<?php //function definition function sayHello(){ echo "Hello World!"; } //function call sayHello(); ?>
This script will produce following result when run from command line −
Output
Hello World!
function with arguments
In following example, a function is defined with two formal arguments
Example
<?php function add($arg1, $arg2){ echo $arg1+$arg2 . "
"; } add(10,20); add("Hello", "World"); ?>
Output
This will produce following result. −
30 PHP Warning: A non-numeric value encountered in line 3
In second call, two string values are given as function arguments. Since PHP doesn't support + operator for strings, a warning is emitted.
function return
User defined function in following example processes the provided arguments and retuns a value to calling environment
Example
<?php function add($arg1, $arg2){ return $arg1+$arg2; } $val=add(10,20); echo "addition:". $val. "
"; $val=add("10","20"); echo "addition: $val"; ?>
Output
This will produce following result. −
addition:30 addition:30
In second call, even if arguments are string, PHP cooerces them into integer and performs addition
function with default argument value
While defining a function , a default value of argument may be assigned. If value is not assigned to such agument while calling the function, this default will be used for processing inside function. In following example, a function is defined with argument having default value
Example
<?php function welcome($user="Guest"){ echo "Hello $user
"; } //overrides default welcome("admin"); //uses default welcome(); ?>
Output
This will produce following result. −
Hello admin Hello Guest
In second call, function is called without passing value. In this case, user argument takes its default value.
function with variable number of arguments
It is possible to define a function with ability to receive variable number of arguments. The name of formal argument in function definition is prefixed by ... token. Following example has add() function that adds a list of numbers given as argument
Example
<?php function add(...$numbers){ $ttl=0; foreach ($numbers as $num){ $ttl=$ttl+$num; } return $ttl; } $total=add(10,15,20); echo "total= $total
"; echo "total=". add(1,2,3,4,5). "
"; ?>
Output
This will produce following result. −
total= 45 total=15
It is also possible to obtain a list of arguments passed to a function with the help offunc_get_args() function. We can run a PHP loop to traverse each value in the list of arguments passed. In that case the function definition doesn't have a formal argument.
Example
<?php function add(){ $numbers=func_get_args(); $ttl=0; foreach ($numbers as $num){ $ttl=$ttl+$num; } return $ttl; } $total=add(10,15,20); echo "total= $total
"; echo "total=". add(1,2,3,4,5). "
"; ?>
Output
This will produce following result. −
total= 45 total=15
function within another function
A function may be defined inside another function's body block. However, inner function can not be called before outer function has been invoked.
Example
<?php function hello(){ echo "Hello
"; function welcome(){ echo "Welcome to TutorialsPoint
"; } } //welcome(); hello(); welcome(); ?>
Remove the comment to call wlcome() bfore hello(). Following error message halts the program −
Fatal error: Uncaught Error: Call to undefined function welcome()
Output
Comment the line and run again
Hello Welcome to TutorialsPoint
Recursive function
A function that calls itself is called recursive function. Calling itself unconditionally creates infinite loop and results in out of memory error because of stack full. Following program calls factorial() function recursively
Example
<?php function factorial($n){ if ($n < 2) { return 1; } else { return ($n * factorial($n-1)); } } echo "factorial(5) = ". factorial(5); ?>
Output
factorial(5) = 120
- Related Articles
- User-Defined Exceptions in Python
- User Defined Literals in C++
- What is user-defined signal handler?
- User defined bridge on Docker network
- User-defined Custom Exception in C#
- Using User-Defined Variables in MySQL
- defined() function in PHP
- C++ set for user defined data type?
- User defined and custom exceptions in Java
- User-defined Exceptions in Python with Examples
- User-defined Exceptions in C# with Example
- What are user-defined exceptions in C#?
- Perform MySQL SELECT INTO user-defined variable
- 2D vector in C++ with user defined size
- Select into a user-defined variable with MySQL
