English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
In this tutorial, you will learn how to create your own custom functions in PHP.
Functions are independent code blocks for executing specific tasks.
PHP has a vast collection of built-in functions that you can directly call in your PHP script to execute specific tasks, such as: gettype(), print_r(), var_dump, and so on.
Please refer to the PHP reference section for a complete list of useful built-in PHP functions.
In addition to built-in functions, PHP also allows you to define your own functions. This is a method to create reusable code packages for executing specific tasks, which can be saved and maintained separately from the main program. Here are some advantages of using functions:
Functions reduce code repetition in the program - Functions allow you to extract commonly used code blocks into a single component. Now, you can execute the same task by calling this function at any location in the script, without having to repeatedly copy and paste the same code block.
Functions make code maintenance easier - Since a function can be created multiple times, any changes made within the function are automatically implemented at all locations without the need to modify multiple files.
Functions make it easier to eliminate errors - When the program is broken down into functions, if any errors occur, you will know exactly which function caused the error and where it can be found. Therefore, error correction becomes much easier.
Functions can be reused in other applications - Since functions are separate from the rest of the script, the same functionality can be easily reused in other applications by simply including the php file that contains these functions.
The next section will show you how to easily define your own functions in PHP.
The basic syntax for creating a custom function can be given:
function functionName() { //The code to be executed }
The declaration of a user-defined function starts with the word function, followed by the name of the function to be created, then parentheses, and finally the function code is placed between curly braces { }.
This is a simple example of a user-defined function that displays the current date:
<?php //Define a function function whatIsToday() { echo "Today is " . date('l', mktime()); } //Call the function whatIsToday(); ?>Test and see‹/›
Note:Function names must start with a letter or underscore character and not with a number, and they can be followed by more letters, numbers, or underscore characters. Function names are case-insensitive.
You can specify parameters when defining a function to accept input values at runtime. The way parameters work is similar to placeholder variables in a function; they are replaced with the values (known as arguments) provided to the function when it is called.
function myFunc($oneParameter, $anotherParameter) { //The code to be executed }
You can define as many parameters as needed. However, for each parameter you specify, you need to pass the corresponding parameter to the function when calling it.
The getSum() function in the following examples takes two integer values as parameters, simply adds them together, and then displays the result in the browser.
<?php //Define a function function getSum($num1, $num2{ $sum = $num1 + $num2; echo "Two numbers $num1and $num2the sum is: $sum"; } //Call the function getSum(10, 20); ?>Test and see‹/›
The output of the above code will be:
two numbers10and2The sum of 0 is : 30
Tip:Parameters are the values you pass to a function, and arguments are the variables that receive parameters within the function. However, in common usage, these terms are interchangeable, that is, parameters are arguments.
You can also create a function with optional parameters - Just insert the parameter name, followed by an equal sign (=), and then the default value, as shown below.
<?php //Define a function function customFont($font, $size=1.5{ echo "<p style=\"font-family: $font; font-size: {$size}em;">Hello, world!/p>"; } //Call the function customFont("Arial", 2); customFont("Times", 3); customFont("Courier"); ?>Test and see‹/›
As you can see, the third call to customFont() does not include the second parameter. This will cause the PHP engine to use the default value of the $size parameter, that is1.5。
A function can return a value to the script that calls it using the return statement. This value can be of any type, including arrays and objects.
<?php //Define a function function getSum($num1, $num2{ $total = $num1 + $num2; return $total; } //Print the returned value echo getSum(5, 10); // Output: 15 ?>Test and see‹/›
A function cannot return multiple values. However, you can achieve a similar result by returning an array, as shown in the following example.
<?php //Define a function function divideNumbers($dividend, $divisor){ $quotient = $dividend / $divisor; $array = array($dividend, $divisor, $quotient); return $array; } //Assign variables as an array list($dividend, $divisor, $quotient) = divideNumbers(10, 2); echo $dividend; // Output: 10 echo $divisor; // Output: 2 echo $quotient; // Output: 5 ?>Test and see‹/›
In PHP, there are two ways to pass parameters to a function: by value and by reference. By default, function parameters are passed by value, so if the parameter value changes within the function, it will not be affected by the function outside. However, to allow the function to modify its parameters, they must be passed by reference.
The method of passing parameters by reference is to add an ampersand (&) before the parameter name in the function definition, as shown in the following example:
<?php /* Define a function that multiplies a number and return the new value */ function selfMultiply(&$number){ $number *= $number; return $number; } $mynum = 5; echo $mynum; // Output: 5 selfMultiply($mynum); echo $mynum; // Output: 25 ?>Test and see‹/›
You can declare variables at any location in a PHP script. However, the location of declaration determines the visibility range of the variable in the PHP program, that is, where the variable can be used or accessed. This accessibility is calledVariable Scope。
By default, variables declared within a function are local variables and cannot be accessed or operated from outside the function, as shown in the following example:
<?php //Define a function function test(){ $greet = "Hello World!"; echo $greet; } test(); // Output: Hello World! echo $greet; //Undefined Variable Error ?>Test and see‹/›
Similarly, if you try to access or import an external variable inside the function, you will get an undefined variable error, as shown in the following example:
<?php $greet = "Hello World!"; //Define a function function test(){ echo $greet; } test(); //Undefined Variable Error echo $greet; // Output: Hello World! ?>Test and see‹/›
As can be seen from the above example, variables declared inside a function cannot be accessed from outside, and similarly, variables declared outside cannot be accessed inside the function. This separation reduces the chance of variables inside the function being affected by variables in the main program.
Tip:You can use the same name for variables in different functions, because local variables can only be recognized by the function that declares them.
In some cases, you may need to import variables from the main program into a function, and vice versa. In this case, you can use the global keyword before the variable within the function. This keyword converts the variable into a global variable, making it visible or accessible both inside and outside the function, as shown in the following example:
<?php $greet = "Hello World!"; //Define a function function test(){ global $greet; echo $greet; } test(); // Output: Hello World! echo $greet; // Output: Hello World! //Assign a new value to the variable $greet = "Goodbye"; test(); // Output: Goodbye echo $greet; // Output: Goodbye ?>Test and see‹/›
You will bePHP Classes and ObjectsFor more information on visibility and access control, see Chapter X.
A recursive function is a function that calls itself repeatedly until it meets a certain condition. Recursive functions are commonly used to solve complex mathematical calculations or handle deeply nested structures, such as printing all elements of a deeply nested array.
The following example demonstrates how recursive functions work.
<?php //Define recursive function function printValues($arr) { global $count; global $items; //Check if $arr is an array if(!is_array($arr)){ die("ERROR: Input is not an array"); } /* Traverse the array, and if the value itself is an array, make a recursive call The function adds the found values to the output item array and increment the counter for each value found1 */ foreach($arr as $a){ if(is_array($a)){ printValues($a); } else{ $items[] = $a; $count++; } } //Return the total count and values in the array return array('total' => $count, 'values' => $items); } //Define nested arrays $species = array( "birds" => array( "Eagle" "Parrot" "Swan" ), "mammals" => array( "Human" "cat" => array( "Lion" "Tiger" "Jaguar" ), "Elephant", "Monkey" ), "reptiles" => array( "snake" => array( "Cobra" => array( "King Cobra" "Egyptian cobra" ), "Viper", "Anaconda" ), "Crocodile", "Dinosaur" => array( "T-rex", "Alamosaurus" ) ) ); //Calculate and print the values in the nested array $result = printValues($species); echo $result['total'] . ' value(s) found: '; echo implode(', ', $result['values']); ?>Test and see‹/›
Note:Be cautious when creating recursive functions, as incorrect code may lead to infinite loops in function calls.