
Building Functions in PHP
A function is a program that performs a specific task. Functions are essentially small blocks of code that help solve a larger problem. Functions are a procedural programming method in PHP and other high-level languages. To understand functions, you need to grasp this concept so that you can continue learning other topics such as object-oriented programming. Therefore, I hope you will master functions.
In this article, we will cover the following topics:
- How to use functions (see more at “php function”)
- The structure of a function
- Different ways to call a function (by value and by reference)
- Rules and scope of functions
Contents
1. How to use functions in PHP
In PHP, a function is used to execute a series of consecutive commands with a starting point and an ending point. A function is defined to perform a specific task. For example, if I write a function to check whether a number is even or odd, the purpose of that function is to determine whether a number is even or odd. Functions can be called from multiple places and different programs.
Let’s say you need to write a program for users to log in to a system, and you will use it in both the backend and frontend applications. But after some time, you want to modify some information during the check. In that case, you would have to go into those two programs and make the changes, which is troublesome because it leads to redundancy and makes it difficult to manage and maintain the program. However, if you use a function, you only need to modify it within that function.
2. The structure of a function in PHP
The general syntax for declaring a function in PHP is:
<?php function func_name($vars){ // code statements return $val; } ?>
In this syntax:
func_name
is the name of the function.$vars
represents the variables that will be passed into the function.return $val
indicates that the function will return the value$val
. If the function does not return any value, there won’t be areturn
statement.
Example:
<?php // Number to check $number = 12; // Call the is_even function and pass the number variable as an argument // Since the is_even function returns true/false, we can use it in an if statement like this if (is_even($number)){ echo 'Even number'; } else { echo 'Odd number'; } // The is_even function returns true if $number is even, and false otherwise. // The $number variable is the input parameter of the function, representing the number to be checked. function is_even($number){ if ($number % 2 == 0) return true; else return false; } ?>
The is_even
function is responsible for checking whether a number is even or odd. If the number is even, it returns true
; otherwise, it returns false
. You can check any number by passing it as an argument, which is represented by the variable $number
. In the main program, we call the is_even
function and check if it returns true
or false
. If it returns true
, we display “Even number”; otherwise, we display “Odd number”.
The is_even
function is considered a function with a return value because it contains a return
statement. If you want the is_even
function to not return a value and instead directly display the result, you can modify it as follows:
<?php // Number to check $number = 12; // Call the is_even function and pass the number variable as an argument is_even($number); // This function is responsible for outputting "Even number" if the input variable ($number) // is an even number, and "Odd number" otherwise. function is_even($number){ if ($number % 2 == 0){ echo 'Even number'; } else { echo 'Odd number'; } } ?>
When you read this, you may wonder why functions in PHP can be placed at the bottom while the preceding lines of code still understand them. This is because PHP follows the principle of interpreting code from top to bottom and from left to right. Functions in PHP can be placed anywhere within a file, and you can freely call them anywhere within the same file.
Passing multiple variables to a function in PHP
The variables passed to a function in PHP can be of any type (refer to the PHP data types tutorial). Additionally, there is no limit to the number of variables that can be passed. In the example provided:
<?php function calculate_sum($a, $b){ return $a + $b; } ?>
This function calculates the sum of two variables passed to it, with the variables separated by commas. In your main program, you can do the following:
<?php $number1 = 12; $number2 = 13; echo calculate_sum($number1, $number2); function calculate_sum($a, $b){ return $a + $b; } ?>
I intentionally named the variables $number1
and $number2
to avoid confusion with the variables used in the calculate_sum function. The purpose is to prevent misunderstandings that the variables passed to a function must have the same names as the variables in the main program.
Assigning default values to function parameters
In PHP, if you declare a function with two parameters but only pass one argument when using it, the system will throw an error. However, in practice, you may want to have functions that do not require all parameters to be passed. Therefore, PHP provides a feature that allows us to assign default values to function parameters. Please refer to the following example:
<?php $number1 = 12; $number2 = 13; // Only pass two arguments echo calculate_sum($number1, $number2); // $c has a default value assigned // This function calculates the sum of three numbers function calculate_sum($a, $b, $c = false){ $sum = $a + $b; if ($c !== false){ // If $c is passed (since false is the default value) $sum += $c; // Add $c to the sum } return $sum; } ?>
In the above example, the calculate_sum function has three parameters, including $c, which is assigned the value of false by default. The function calculates the sum of three numbers. If $c is not passed, it only calculates the sum of the first two numbers.
Actual Parameters and Formal Parameters
The variables defined within a function are called formal parameters, while the variables passed into the main program are called actual parameters.
<?php // Main program $number = 12; $flag = check_prime_number($number); // Function to check prime numbers function check_prime_number($number){ // code } ?>
The parameter $number
in the function check_prime_number is referred to as a formal parameter, while the variable $number in the main program is referred to as an actual parameter.
Global Variables and Local Variables
This definition is nothing new for languages like C, C++. However, in PHP, their usage is slightly different compared to these languages. Global variables are variables declared in the main program, while local variables are variables declared within functions.
Example:
<?php // Global variable $global_variable = 12; function check(){ // Local variable $local_variable = 13; // Accessing the global variable global $global_variable; // Checking if the remainder of the local variable divided by the global variable is zero // Returns true if the remainder is zero, false otherwise if ($local_variable % $global_variable == 0){ return true; } else{ return false; } } ?>
Looking at the comments, you should understand it, right? In PHP, to access the value of a global variable, we use the global $variable_name
statement. Although this is less commonly used in frameworks, it is frequently utilized in CMS platforms like WordPress to retrieve global variables.
Static Variables
Static variables are fixed variables within functions. Unlike global variables, they are not accessible outside the function, meaning they are only known within the function. However, their values are retained after each function call. To declare a static variable, we use the keyword static $variable_name;
.
Example:
<?php // Checking function function check(){ // Static variable static $a = 0; $a++; echo $a; } check(); check(); ?>
When running this code, the output will be 1 and 2 because in the first function call, the variable $a
is incremented by 1 and displayed as 1. Since $a
is a static variable, it is stored in memory. In the second function call, $a
is incremented by 1 again, resulting in 2 being displayed, and of course, the value 2 is retained in memory for subsequent function calls.
3. Calling Functions in PHP
We have two common ways to call functions in PHP.
Passing by Value:
By default, all arguments passed to a function are passed by value. This means that when the arguments are passed to the called function, their values are passed through temporary variables (formal parameters). All operations are performed on these temporary variables, so they do not affect the original variables. This means that if we pass by value, any changes to the argument’s value within the function will not affect its value outside the function.
Example:
<?php // Variable $a = 1; // Function to increase the value of the passed parameter by 1 function increment_by_1($a){ return $a + 1; } // Output the return value of the function echo increment_by_1($a); // Output the value of the variable echo $a; ?>
The output displayed will be 2 and 1. As you can see, the variable $a
retains its original value of 1 after the function finishes. However, within the function, the variable $a
has a value of 2.
Passing by Reference:
When arguments are passed by value, the values of the function’s arguments are not changed. However, there are situations where you may want those values to be modified. In such cases, you need to pass variables to the function as references.
Example:
<?php // Variable $a = 1; // Function to increment the value of the parameter by 1 function increment_by_1(&$a){ $a = $a + 1; return $a; } // Output the return value of the function echo increment_by_1($a); // Output the value of the variable echo $a; ?>
The result displayed on the screen will be 2 and 2. Therefore, the variable $a has been changed.
The difference in this code compared to the previous one is the presence of the &
symbol before the variable $a in the increment_by_1
function. This is the syntax in PHP that informs the compiler that it is a reference variable.
4. Rules and Scope of Functions
A function can call another function, meaning that within the body of function A, you can call function B, and within the body of function B, you can call function C. This is known as function calling.
Example:
<?php // List of functions function A(){ B(); } function B(){ C(); } function C(){ echo 'C'; } // Main program calls function A A(); // Output: 'C' ?>
Do you see the interesting part? I find it a bit challenging because you have to think through each line of code like this :D. You can run the code following the rule from top to bottom and from left to right, debugging each line to get the result. Once you get familiar with it, you will be able to manage your own code.
Usually, people write functions in a separate PHP file, and the main program is in another PHP file. In the main program, you call the functions you want to use. I will address this topic in another lesson.
5. Conclusion
In this lesson, you have learned how to work with functions in PHP, which is a fundamental concept in structured programming and a stepping stone for learning object-oriented programming. Therefore, it is important to grasp this concept before moving on to the next lessons. In the next lesson, we will explore recursive algorithms in PHP.
Related Articales
Comments
-
Download and Install Vertrigo Server
May 25, 2023.84 views -
Declaring variables in PHP, common types of variables encountered
May 25, 2023.84 views -
Data types in PHP and their corresponding variable types
May 25, 2023.84 views -
Operators and expressions in PHP
May 25, 2023.84 views -
The if else statement in PHP
May 25, 2023.84 views -
The switch case statement in PHP
May 25, 2023.84 views -
The for loop in PHP
May 25, 2023.84 views -
While and do-while loops in PHP
May 25, 2023.84 views -
The foreach Loop in PHP
May 25, 2023.84 views -
The break, continue, goto, die, exit statements in PHP
May 25, 2023.84 views -
Building Functions in PHP
May 25, 2023.84 views -
Recursive Algorithm in PHP
May 25, 2023.84 views -
Bubble Sort Algorithm in PHP
May 25, 2023.84 views -
Linear Search Algorithm in PHP
May 25, 2023.84 views -
The technique of sentry placement in PHP
May 25, 2023.84 views -
Flagging technique in PHP
May 25, 2023.84 views -
Selection Sort Algorithm in PHP
May 25, 2023.84 views
Tags
© copyright 2021 Courseplus