Web programming

Functions and How to Use Them in PHP

Ngoc Phuong

Ngoc Phuong

2021-05-23 . 199 view

Functions are extremely important in PHP, and one of the strengths of PHP is its functions. PHP has over 1000 pre-built functions, and in addition, you can create your own custom functions depending on your project.

I. Built-in Functions in PHP

As mentioned above, PHP has over 1000 built-in functions that you can freely use in your programs without having to build them yourself.

To find out what the built-in functions in PHP are, you can visit the following: Built-In Functions in PHP.

This article will guide you on how to write a function and how to use functions in PHP.

II. The Concept of Functions in PHP

1. What is a Function?

A function is simply a block of statements used to perform a recurring task in a program.

A function will not execute automatically if it is not called.

2. How to Define a Function and How to Call a Function

The syntax for defining a function is as follows:

function functionName() {
  // code 
}

Note:

  • The function name must start with a letter or an underscore. Function names are NOT case-sensitive.
  • It's good practice to name the function according to its purpose to avoid having to comment on its function, making it understandable to others.

Example: Define a function that outputs "Hello World" and call it.

function writeMsg() {
  echo "Hello world!";
}

writeMsg(); // Call function

3. Functions with Arguments

When building a function with arguments, keep the following in mind:

  • Information is passed to the function through arguments.
  • A function can have multiple arguments.
  • Each argument is like a variable and is separated by commas.

Example: We have a function that calculates the sum of a and b, where a and b are any numbers. In this case, we can construct a function with two arguments a and b as follows:

function crystalTong($a, $b){
$total = $a + $b;
return $total;
}
// Call the function with argument values
echo crystalTong(5,10);
echo crystalTong(2,3);
echo crystalTong(7,10);
echo crystalTong(8,3);

In the above example, you will see that when assigning arguments, we do not need to declare the data type; PHP will automatically define the most suitable data type for the argument and then execute the command. The example is also the same function, but if I pass argument b as a string, PHP will automatically cast the string to an int to perform the calculation. You can run the following example for a better understanding.

function crystalTong($a, $b){
$total = $a + $b;
return $total;
}
// Call the function with argument values, argument b passes string
echo TinhTong(5, "10 days"); // "10 days" is changed to int(10) and it returns 15

That's when you haven't declared a data type. What if you have declared a data type? In the case that you have declared a data type, PHP will still automatically cast the string to int to calculate, and the program does not error out. If you don't believe it, you can run the following example to test it.

function crystalTong(int $a, int $b){
$total = $a + $b;
return $total;
}
// Call the function with argument values, argument b passes string
echo TinhTong(5, "3 days"); // "3 days" is changed to int(3) and it returns 8

Clearly, in the two cases above, you pass the wrong argument, but the program still runs without throwing an error, which can be very dangerous. For this reason, the PHP language is often considered quite loose. Fortunately, PHP 7 has added strict type declarations, which will raise a "Fatal Error" if the data type does not match. Adding strict declarations is also very simple; you only need to add the line declare(strict_types=1); at the top of the PHP file.

Now let's try declaring strict for the above example to understand this issue further.

declare(strict_types=1); // declare strict
function crystalTong(int $a, int $b){
$total = $a + $b;
return $total;
}
// Call the function with argument values, argument b passes string
echo TinhTong(5, "3 days"); // As a result, the following error line will appear: PHP Fatal error: Uncaught TypeError: Argument 2 passed to sperm() must be of the type integer, string given, called in /home/KFBaXH/prog.php on line 8 and defined in /home/KFBaXH/prog.php:3 Stack trace: #0 /home/KFBaXH/prog.php(8): TinhTong(5, '3 ng\xC3\xA0y') #1 {main} thrown in / home/KFBaXH/prog.php on line 3

When declaring strict, it means a strict declaration that forces everything to be used as defined.

4. Functions with Default Arguments

When building a function with default arguments, if you do not pass any arguments, the function will automatically take the default value that was declared at the outset to execute the program.

Example: We have a function that assigns any height, with a default value = 50, as follows:

declare(strict_types=1); // declare strict
function setHeight(int $height = 50) {
 echo "Height is : $height 
";
}

setHeight(350); // Result 350
setHeight(); // No arguments are passed, so the default value will be 50

5. Declaring Return Type for Functions

Typically, when writing functions, we often use the return statement to retrieve the return value of a function as follows:

declare(strict_types=1); // declare strict
function setHeight(int $height = 50) {
 return $height;
}

echo "Height is: ".setHeight(350); // Result 350

In PHP 7, there is an additional part for declaring types for return statements. To declare a type for a function's return, add a colon (:) and the data type before the opening brace ({) when declaring the function. Refer to the following example for a better understanding.

declare(strict_types=1); // declare strict
function tinhTong(float $a, float $b) : float {
 return $a + $b;
}
echo tinhTong(1.2, 5.2); // The return type will be float, because the return type has been declared for the return statement

Additionally, you can declare a different return type from the argument, but you must ensure that the result matches the type declared for the return. For instance, we have a function that calculates the sum of a and b, with a and b as float data types, and the declared return type as int, as follows:

declare(strict_types=1); // declare strict
function tinhTong(float $a, float $b): int {
 return (int)($a + $b);
}
echo tinhTong(1.2, 5.8);

6. Functions with Reference Arguments

When arguments are passed by value, the values of those arguments do not change. However, in some cases, you want the value of these arguments to change accordingly, so you need to pass variables into the function by reference. To turn a function's argument into a reference type, we use the & operator before the argument, refer to the following example:

function addFive(&$value) {
 $value += 5;
}

$num = 5;
addFive($num); // Increase by 5 units
echo $num; // The result is 10

With that, I've shared all about functions in PHP, which can be said to be one of the very important and useful bits of knowledge when working with PHP. It will help you optimize your code, avoid code duplication, and make the code more professional...
 

Ngoc Phuong
Ngoc Phuong

Web Developer

Thank you for visiting my website. My name is Ngoc Phuong, and I have over 10 years of experience in website development. I am confident in stating that I am an expert in creating impressive and effective websites. If you need a website designed, please feel free to contact me via email at [email protected].

0 feedback