- PHP Functions Passing Arguments by Reference
- What is Pass By Reference and Pass By Value in PHP?
- Example
- Output
- Explanation
- Note
- Example
- Output
- Explanation
- PHP Functions
- PHP Built-in Functions
- PHP User Defined Functions
- Create a User Defined Function in PHP
- Syntax
- Example
- PHP Function Arguments
- Example
- Example
- PHP is a Loosely Typed Language
- Example
- Example
- PHP Default Argument Value
- Example
- PHP Functions — Returning values
- Example
- PHP Return Type Declarations
- Example
- Example
- Passing Arguments by Reference
- Example
- PHP Function Parameters
- Introduction to the PHP function parameters
- Trailing comma (,)
- Passing arguments by values
- Passing arguments by reference
- Summary
PHP Functions Passing Arguments by Reference
Function arguments can be passed «By Reference», allowing the function to modify the variable used outside the function:
function pluralize(&$word) < if (substr($word, -1) == 'y') < $word = substr($word, 0, -1) . 'ies'; >else < $word .= 's'; >> $word = 'Bannana'; pluralize($word); print $word; // Bannanas
Object arguments are always passed by reference:
function addOneDay($date) < $date->modify('+1 day'); > $date = new DateTime('2014-02-28'); addOneDay($date); print $date->format('Y-m-d'); // 2014-03-01
To avoid implicit passing an object by reference, you should clone the object.
Passing by reference can also be used as an alternative way to return parameters. For example, the socket_getpeername function:
bool socket_getpeername ( resource $socket , string &$address [, int &$port ] )
This method actually aims to return the address and port of the peer, but since there are two values to return, it chooses to use reference parameters instead. It can be called like this:
if(!socket_getpeername($socket, $address, $port)) < throw new RuntimeException(socket_last_error()); >echo "Peer: $address:$port\n";
The variables $address and $port do not need to be defined before. They will:
- be defined as null first,
- then passed to the function with the predefined null value
- then modified in the function
- end up defined as the address and port in the calling context.
PDF — Download PHP for free
What is Pass By Reference and Pass By Value in PHP?
In this article, we will learn about pass by value and pass by reference in PHP.
Now, let’s understand these two concepts in detail.
In PHP generally, 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.
In some cases we may need to modify function arguments, So to allow a function to modify its arguments, they must be passed by reference.
Let’s begin with passed by reference. 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
Let’s test this with a simple example.
Output
Explanation
Here we have declared variable $a and passing it as pass by reference to the function calculate(). So as the principle says if the value of the $a gets changed inside the function then it will be also going to change outside the function.
Note
There is no reference sign on a function call — only on function definitions. Function definitions alone are enough to correctly pass the argument by reference. This is deprecated in 5.4 version of PHP when you use to calculate(&$a); it throws an error.
Example
Let’s test an example to understand pass by value.
Output
Explanation
Here we have passed the value to the function calculate() as pass by value. Its value gets changed inside the function but that is not reflected outside the function. The value of the variable remains the same outside the function.
PHP Functions
PHP has more than 1000 built-in functions, and in addition you can create your own custom functions.
PHP Built-in Functions
PHP has over 1000 built-in functions that can be called directly, from within a script, to perform a specific task.
Please check out our PHP reference for a complete overview of the PHP built-in functions.
PHP User Defined Functions
Besides the built-in PHP functions, it is possible to create your own functions.
- A function is a block of statements that can be used repeatedly in a program.
- A function will not execute automatically when a page loads.
- A function will be executed by a call to the function.
Create a User Defined Function in PHP
A user-defined function declaration starts with the word function :
Syntax
Note: A function name must start with a letter or an underscore. Function names are NOT case-sensitive.
Tip: Give the function a name that reflects what the function does!
In the example below, we create a function named «writeMsg()». The opening curly brace ( < ) indicates the beginning of the function code, and the closing curly brace ( >) indicates the end of the function. The function outputs «Hello world!». To call the function, just write its name followed by brackets ():
Example
writeMsg(); // call the function
?>
PHP Function Arguments
Information can be passed to functions through arguments. An argument is just like a variable.
Arguments are specified after the function name, inside the parentheses. You can add as many arguments as you want, just separate them with a comma.
The following example has a function with one argument ($fname). When the familyName() function is called, we also pass along a name (e.g. Jani), and the name is used inside the function, which outputs several different first names, but an equal last name:
Example
familyName(«Jani»);
familyName(«Hege»);
familyName(«Stale»);
familyName(«Kai Jim»);
familyName(«Borge»);
?>
The following example has a function with two arguments ($fname and $year):
Example
function familyName($fname, $year) echo «$fname Refsnes. Born in $year
«;
>
?php
familyName(«Hege», «1975»);
familyName(«Stale», «1978»);
familyName(«Kai Jim», «1983»);
?>
PHP is a Loosely Typed Language
In the example above, notice that we did not have to tell PHP which data type the variable is.
PHP automatically associates a data type to the variable, depending on its value. Since the data types are not set in a strict sense, you can do things like adding a string to an integer without causing an error.
In PHP 7, type declarations were added. This gives us an option to specify the expected data type when declaring a function, and by adding the strict declaration, it will throw a «Fatal Error» if the data type mismatches.
In the following example we try to send both a number and a string to the function without using strict :
Example
function addNumbers(int $a, int $b) return $a + $b;
>
echo addNumbers(5, «5 days»);
// since strict is NOT enabled «5 days» is changed to int(5), and it will return 10
?>?php
To specify strict we need to set declare(strict_types=1); . This must be on the very first line of the PHP file.
In the following example we try to send both a number and a string to the function, but here we have added the strict declaration:
Example
function addNumbers(int $a, int $b) return $a + $b;
>
echo addNumbers(5, «5 days»);
// since strict is enabled and «5 days» is not an integer, an error will be thrown
?>
The strict declaration forces things to be used in the intended way.
PHP Default Argument Value
The following example shows how to use a default parameter. If we call the function setHeight() without arguments it takes the default value as argument:
Example
setHeight(350);
setHeight(); // will use the default value of 50
setHeight(135);
setHeight(80);
?>
PHP Functions — Returning values
To let a function return a value, use the return statement:
Example
PHP Return Type Declarations
PHP 7 also supports Type Declarations for the return statement. Like with the type declaration for function arguments, by enabling the strict requirement, it will throw a «Fatal Error» on a type mismatch.
To declare a type for the function return, add a colon ( : ) and the type right before the opening curly ( < )bracket when declaring the function.
In the following example we specify the return type for the function:
Example
You can specify a different return type, than the argument types, but make sure the return is the correct type:
Example
Passing Arguments by Reference
In PHP, arguments are usually passed by value, which means that a copy of the value is used in the function and the variable that was passed into the function cannot be changed.
When a function argument is passed by reference, changes to the argument also change the variable that was passed in. To turn a function argument into a reference, the & operator is used:
Example
Use a pass-by-reference argument to update a variable:
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.