- 5 Types of Functions in PHP with Examples
- Two major types of functions in PHP:
- 1. Built-in function:
- 2. User Defined Function:
- Advantage of PHP functions:
- Create a function in PHP:
- Function Parameter or Arguments in PHP :
- Default Values for Function parameter in PHP:
- Returning Values from Functions in PHP:
- Parameter passing to Functions in PHP:
- 1. Pass by Value in PHP:
- 2. Pass by Reference in PHP:
- PHP Function Parameters
- Introduction to the PHP function parameters
- Trailing comma (,)
- Passing arguments by values
- Passing arguments by reference
- Summary
- Passing parameter in function in php
- PHP Functions: Scope Variable, Passing Parameter, Default, Parameters By reference, Returns
- Syntax of PHP Functions:
- Scope variables:
5 Types of Functions in PHP with Examples
A function is a piece of code which takes one more input in the form of parameter and does some processing and returns a value.
A function is block of code written in a program to perform some specific task.
PHP has over 1000 built-in functions that can be called directly, from within a script, to perform a specific task.
Two major types of functions in PHP:
1. Built-in function:
PHP has over 1000 built-in functions that can be called directly, from within a script, to perform a specific task. This functions are already coded and stored in form of functions.
2. User Defined Function:
We can declare and call user-defined functions easily. PHP allows our own customised function called the user-defined function. Using this we can create our own package of code and use it.
Advantage of PHP functions:
Code Reusability : If we have a common code that we would like to use at various parts of a program, we can simply contain it within a function and call it whenever required. It defines only once can be invoked many times, like in other programming languages.
Less Code : In PHP, it saves a lot of code don’t need to write the logic many times. By the use of function, you can write the logic only once and reuse it.
Easy to Understand : It is easier to understand the flow of the application because every logic is divided in the form of function.
Create a function in PHP:
Example of simple function call in PHP:
Function Parameter or Arguments in PHP :
We can pass the information in PHP function through argument which is separated by comma. The information or variable, within the functions parenthesis are called parameters. These are used to hold the values executable during runtime. A user is free to take in as many parameters as he wants, separated with a comma(,) operator. These parameters are used to accept inputs during runtime.
function function_name($first_parameter, $second_parameter)
Example of Function Parameter or argument in PHP:
Default Values for Function parameter in PHP:
PHP allows us to set default argument values for function parameters. If we do not pass any argument for a parameter with default value then PHP will use the default set value for this parameter in the function call.
Example of default values function parameter in PHP:
fun_demo("Ram", 15); fun_demo("Lakhan"); ?>
Ram is 15 years old Lakhan is 12 years old
Returning Values from Functions in PHP:
The return keyword is used to return value back to part of program.
Example of returning values from function in PHP:
$value = cube(4, 4, 4); echo "Cube of 4 is $value"; ?>
Parameter passing to Functions in PHP:
PHP allows two ways in which an argument can be passed into a function:
1. Pass by Value in PHP:
We followed to pass the arguments to the function with passed by value approach. We are following this practice because if the value of the argument within the function is changed, it does not get changed outside of the function.
2. Pass by Reference in PHP:
As it is already mentioned we can pass a variable by reference to a function so the function can modify the variable. To begin the process of passing the parameters passed by reference, prepend an ampersand (&) to the argument name in the function definition.
Example of Parameter passing to function in PHP:
function ref(&$num) < $num += 5; return $num; >$n = 10; val($n); echo "The original value is still $n \n"; ref($n); echo "The original value changes to $n"; ?>
The original value is still 10 The original value changes to 15
We have covered In this article we are going to cover functions in PHP, Types of functions in PHP, Advantage of PHP functions, Arguments in PHP, Function parameter in PHP.
Related Articles:
PHP Function Parameters
Summary: in this tutorial, you’ll learn about the function parameters and pass arguments by value and reference.
Introduction to the PHP function parameters
A function can have zero or more parameters:
function function_name(parameter_list)
Code language: HTML, XML (xml)
When a function has multiple parameters, you need to separate them using a comma ( , ).
The following example defines the concat() function that concatenates two strings into one:
function concat($str1, $str2) < return $str1 . $str2; >
Code language: HTML, XML (xml)
The concat() function has two parameters $str1 and $str2 .
When you call the concat() function, you need to pass two arguments that correspond to the parameters. For example:
function concat($str1, $str2) < return $str1 . $str2; > $greeting = concat('Welcome ', 'Admin'); echo $greeting;
Code language: HTML, XML (xml)
In this example, the $str1 will take the first argument ‘Welcome ‘ , and the $str2 will take the second argument ‘Admin’ .
PHP will raise an error if the number of arguments you pass to the function is less than the number of parameters. For example:
function concat($str1, $str2) < return $str1 . $str2; > $greeting = concat('Welcome'); echo $greeting;
Code language: HTML, XML (xml)
When you pass multiple arguments to a function, you can break the list the arguments vertically to make the code more readable like this:
function concat($str1, $str2) < return $str1 . $str2; > $greeting = concat( 'Welcome ', 'Home' ); echo $greeting;
Code language: HTML, XML (xml)
It’s a good practice to list arguments vertically when the argument list is long.
Trailing comma (,)
From PHP 7.0, the argument list may contain a trailing comma ( , ) which the PHP interpreter will ignore. For example:
$greeting = concat( 'Welcome ', 'Home', );
Code language: PHP (php)
Starting from PHP 8.0, you can place the trailing comma (,) in the parameter list like this:
function concat( $str1, $str2, ) < return $str1 . $str2; >
Code language: PHP (php)
Passing arguments by values
Consider the following example:
$counter = 1; function increase($value) < $value+= 1; echo $value.
; // 2 > // increase the counter increase($counter); echo $counter .
; // 1
Code language: HTML, XML (xml)
- First, define the $counter variable and initialize its value to one.
- Second, define the increase() function that increases the argument by one and displays it.
- Third, call the increase() function and pass the $counter variable into the function.
- Finally, display the $counter variable.
When you pass the $counter variable to the increase() function, the function increases its value by one. Therefore, when you display the value of the $counter inside the function, you’ll get two.
However, after the function call, the value of the counter is still one. It means that the increase() function doesn’t increase the $counter variable outside the function.
What happens is that when you pass the $counter to the increase() function, the function copies the $counter variable and modifies the copy. It doesn’t change the original variable. The $counter variable doesn’t change.
When the value of an argument within the function is changed and doesn’t get changed outside the function, it is passed by value.
By default, arguments are passed by values in PHP. If you want a function to change its arguments, you need to pass the arguments by reference.
Passing arguments by reference
To pass an argument by reference, you prepend the operator ( & ) to the parameter name in the function definition like this:
$counter = 1; function increase( &$value ) < $value += 1; echo $value .
; // 2 > // increase the counter increase($counter); echo $counter .
; // 2
Code language: HTML, XML (xml)
In this example, the change of the $counter variable reflects both inside and outside the function.
Summary
- Separate parameters by a comma ( , ). Since PHP 8.0, the parameter list can have the trailing comma ( , ) which the PHP interpreter ignores.
- By default, arguments are passed by value in PHP.
- Prepend parameters by an ampersand ( & ) to pass arguments by reference.
Passing parameter in function in php
To experiment on performance of pass-by-reference and pass-by-value, I used this script. Conclusions are below.
#!/usr/bin/php
function sum ( $array , $max ) < //For Reference, use: "&$array"
$sum = 0 ;
for ( $i = 0 ; $i < 2 ; $i ++)#$array[$i]++; //Uncomment this line to modify the array within the function.
$sum += $array [ $i ];
>
return ( $sum );
>
$max = 1E7 //10 M data points.
$data = range ( 0 , $max , 1 );
$start = microtime ( true );
for ( $x = 0 ; $x < 100 ; $x ++)$sum = sum ( $data , $max );
>
$end = microtime ( true );
echo «Time: » .( $end — $start ). » s\n» ;
/* Run times:
# PASS BY MODIFIED? Time
— ——- ——— —-
1 value no 56 us
2 reference no 58 us
3 valuue yes 129 s
4 reference yes 66 us
1. PHP is already smart about zero-copy / copy-on-write. A function call does NOT copy the data unless it needs to; the data is
only copied on write. That’s why #1 and #2 take similar times, whereas #3 takes 2 million times longer than #4.
[You never need to use &$array to ask the compiler to do a zero-copy optimisation; it can work that out for itself.]
2. You do use &$array to tell the compiler «it is OK for the function to over-write my argument in place, I don’t need the original
any more.» This can make a huge difference to performance when we have large amounts of memory to copy.
(This is the only way it is done in C, arrays are always passed as pointers)
3. The other use of & is as a way to specify where data should be *returned*. (e.g. as used by exec() ).
(This is a C-like way of passing pointers for outputs, whereas PHP functions normally return complex types, or multiple answers
in an array)
5. Sometimes, pass by reference could be at the choice of the caller, NOT the function definitition. PHP doesn’t allow it, but it
would be meaningful for the caller to decide to pass data in as a reference. i.e. «I’m done with the variable, it’s OK to stomp
on it in memory».
*/
?>
PHP Functions: Scope Variable, Passing Parameter, Default, Parameters By reference, Returns
If the use of PHP Functions is a definite advantage, a preliminary design step remains necessary in order to clearly define the functions that will have to be developed and to target their respective roles. Most importantly, the preliminary step is to set the entry rules / output of each function, this so that each developer knows in advance the parameters it should send to the function and what it should return after processing performed. If the PHP Functions are known from the start, then everyone can start to understand them. use in its code even before putting said functions into production.
Syntax of PHP Functions:
The function is a subroutine isolated from the rest of the code and usable by a simple call from any part of the program. The syntax for declaring a simple function is as follows:
This code displays nothing until it is called like this:
The previous case is a good example of a function declaration and use of it at inside the main program. We can see the benefit of the definition of the function in case the task of it is repetitive and should generate a lot of source code.
Note: Choosing the name of a function To make your code easier to read, don’t hesitate to give your functions a evocative name. As with variables, reading your program is facilitated if these elements have explicit names. If the program functions are called function1(), function2() and function3(), maintenance does not will be that more difficult. Do not give your PHP Functions a name that is too cryptic or that can have several meanings. Avoid function names that are too short for them to be not used more than once in your program. For example, for a function that must count a number of people present on a web page, do not call it not just counter(), but rather onlinePersonCounter().
Scope variables:
As we said, a function is nothing more than a piece of code isolated from the program main. It is therefore no surprise that you will learn that it is possible to define variables within its functions. On the other hand, what must be remembered is that the variables thus defined are not accessible from the rest of the program (they have a local scope), like the demonstrate the following example: