Page Content

Tutorials

PHP Functions: Arguments, Return Values & Scope Explained

Introduction to PHP Functions

PHP is a standalone code module that carries out a single, clearly defined task. You can write more structured and reusable code by using functions. it can be made more readable, adaptable, and maintainable by packaging it into functions, which allow you to run that block frequently throughout your script without having to type the same code over. You can develop your own user-defined functions in PHP in addition to the language’s built-in or pre-defined functions.

Defined Functions

Functions Defined by Users The function keyword is used to define your own functions. The function keyword, function name, two parentheses (), and the code block contained in curly brackets {} are the first elements of a function declaration. Any text that complies with PHP‘s naming guidelines, usually beginning with a letter or underscore, can be used as the function name. There is no case difference in function names.

The fundamental syntax for defining a user-defined function is as follows:

<?php
function functionName() { // function definition
    // code to be executed 
}
?>

A function is called using its name enclosed in parenthesis once it has been defined:

<?php
function my_function() { 
    echo 'My function was called';
}
my_function(); // Calling the function 
?>

The message “My function was called” would appear as a result.

Function Arguments and Return Values

Return Values and Function Arguments Inputs are frequently necessary for functions to carry out their tasks. These inputs are referred to as arguments or parameters. In the function declaration, parameters are declared inside brackets, with commas between them if more than one is required. Functions can take in a list of all the parameters or none at all. When you call the function, you supply argument values to transmit data into it. Although any form of data can be used as a parameter, certain methods typically call for particular data types. Arguments can be supplied by reference or by value, which is the most popular method when a copy is made.

<?php
function greetPerson($name) { // Function definition with a parameter $name 
    echo "Hi there, ".$name; 
}
greetPerson("Fabio"); // Calling the function, passing an argument 
greetPerson("Michael");
?>

This would result in: Hello, Fabio Hello, Michael

A result can also be returned by a function. A value is returned to the caller using the return statement. Additionally, the function’s execution is instantly stopped with the return statement.

Here is an example with arguments and a return value:

<?php
function addNumbers($a, $b) { 
    $sum = $a + $b; 
    return $sum;  // Returns the calculated sum
}
$total = addNumbers(2, 2); // Calling the function and assigning the returned value 
echo "The sum is: " . $total; // Output: "The sum is: 4" 
?>
Another example using return:
<?php
function square ($x) { 
    return $x*$x; 
}
print 'The square of 5 is ' . square(5);  // Output: The square of 5 is 25
?>

Variable Scope with in Functions Scope

Changeable Scope of Functions The environment in which a variable is defined and accessible is known as its scope. A local function scope is introduced by functions. By default, any variable defined or used inside a function is restricted to this local scope. This means variables and parameters inside a function are unreachable outside of it. By default, global scope variables are unreachable from within a function.

Take a look at this example to see scope:

This results in the following output: Inside the function, $x is 0. $4 is $x outside of function. Although 0 and 4 are used in the idea remains the same: the local variable by default conceals the global one.

<?php
$var = 1; // $var in the global scope 
function func() {
    $var = 2; // This creates a *local* variable $var inside the function 
    print "\$var inside function is: $var <br />";  // Outputs 2 
}
func(); 
print "\$var outside of function is: $var <br />"; // Outputs 1 (the global $var is unchanged)
?>

It is necessary to use the global keyword specifically in order to access a global variable from within a function:

<?php
$var = 1; // Global variable 
function func_global() {
    global $var; // Declare that we want to use the global $var
    $var = 2; // This now changes the global $var 
}
func_global(); 
print $var; // Outputs 2 
?>

Both inside and outside of functions, special superglobal variables (such as $_GET and $_POST) are visible. Depending on whether the include/require is in the global scope or within a function, using the include() or require() commands does not alter the variable scope.

Pre-defined Functions

Functions that are predefined (such as echo, print, exit, and death) PHP has a vast library of pre-defined or built-in functions; the documentation lists hundreds of them. From math and string manipulation to file management and database connectivity, these methods cover a broad range of applications. For an extensive list, it is advised to see the PHP Function Reference.

The following are a few fundamental pre-defined output and script termination constructs and functions:

  • echo: This isn’t exactly a function; it’s a language construct. It is frequently used to output data, including strings. Echo is typically faster than print and can produce several strings separated by commas. When PHP is used with echo, numerical variables are immediately converted to strings.
  • print: A function is this. It outputs a string and is comparable to echo. Print returns a value (always 1) and can only emit a single string, in contrast to echo. If a more sophisticated expression needs to produce output, this return value capability may be helpful.
  • exit and die: These two linguistic constructs both stop the current script from running. An alias for exit() is die(). They can optionally emit a message, usually in reaction to an error, and are frequently used to halt script execution.

String functions like strlen() (which yields the length of a string), substr() (which extracts a substring), and file functions like fopen() (which opens a file) are other instances of pre-defined functions that were described.

Index