As in most programming languages, it is possible to create your own PHP functions that complement the native functions. This allows performing particular operations that are redundant in the application, and solve a problem by breaking it into several small problems and solutions.
This tutorial shows users features. We define first what is a function and a procedure. Then see how you declare a function and ask her to return one or more values, before addressing the principles of visibility and variable scope. Finally we will explain the mechanisms of passing parameters (copy and reference) and conclude with the functions to endless arguments.
We’ll be covering the following topics in this tutorial:
What is a function / user procedure?
In addition to the native functions that do not require import library before they call, there are custom functions. These are created by the programmer itself and stored in an external library.
More specifically, a user function is defined as an instruction on more or less long and complex. This can be seen as a main program of the subroutine that is called.
There are two types of user functions: functions and procedures. What difference is there in between? The difference between them is the return value. A procedure is a group of instructions that does not return a value after execution. A function, meanwhile, is actually a procedure that returns a value (primitive or complex type) or object.
Finally, a user function may (or may not) take input parameters just as a mathematical function. These parameters can be primitive types (int, float, string, boolean) or structured (array, object).
Declaration of a function
Basic principle
A user function is defined by two main elements. Signed and body. The signature is itself composed of two parts: the name and parameter list. The body, in turn, establishes the sequence of instructions that must be executed.
The declaration of a new function is realized using the function keyword followed by the function name and its arguments. The following code shows it all:
Example declaration of a function
<?php function funcname ($param1, $param2, ...) { // Block instructions } ?>
When declaring a function, its name and the name of its parameters are totally arbitrary. It is possible to name the function and its arguments in a natural language. Example: browseTable($ table).
Warning: a feature should only be reported once. Otherwise, an error message will be returned by the PHP interpreter.
Let’s take a very simple example of a function (actually procedure) that calculates the sum of the two parameters. The result is stored in a local variable $ sum then displayed using a echo () statement.
Declaration of a procedure
<?php function Sumcalculate ($a, $b) { // Declare the local variable $sum $sum = $a + $b; // Display result echo 'The sum of', $a, 'and' , $b, 'is', $sum; } ?>
Default value
It is possible to apply a default value to a parameter if it is not specified when calling. In our previous example we will apply the default value at $ 5 parameter b.
Assigning a default value to a parameter
<?php function Sumcalculate ($a, $b=5) { // Declare the local variable $ sum $sum = $a + $b; // Display result echo 'The sum of ', $a, ' and ', $b, ' is ', $sum; } ?>
Return value
As we explained above, there are two kinds of user functions: functions and procedures. Until then, our example was a procedure as referred worthless (or void).
We will now modify our function so that it returns the sum of the two parameters instead of displaying it on standard output.
Declaration of a function
<?php function Sumcalculate ($a, $b) { // Declare the local variable $sum $sum = $a + $b; // Return the sum of the main program return $sum; } ?>
We note here the presence of a new keyword. This is return. The return statement returns the value of the local variable $sum to the main program that calls the function. We will see in the next section how to retrieve this value. The function execution is stopped immediately after execution of the return statement.
A function may also have multiple return statements in his body. Here’s an example that simulates a mechanism verifying that a person is connected.
Example of a function with multiple return statements
<?php function isLog ($connect) { // Test of the input parameter if ($1 === connects) { return true; } return false; } ?>
Here we return a boolean (true or false) depending on the state of the variable $islogs.
Important: A function can return one and only one primitive type value at a time. To return multiple values at once, one must have recourse to the table. The principle is explained right after.
Return multiple values
In special cases of application are asked to a function return multiple values at once. We saw earlier that calling multiple return statements was impossible. To overcome this weakness, PHP authorizes the dismissal of a table of values or a structured type.
Take the example of a function that returns the connection identifiers in a database. This is an example totally arbitrary.
Example forwarding table
<?php function getIdentifiersSql () { return array ('sql.com', 'mylogin', 'myPassword', 'MyDatabase'); } ?>
We could also first declare the local array and assign values before returning it to him as the following code shows.
Statement and reference the table
<?php function getIdentifiersSql () { $arrayIdentifiers = array (); $arrayIdentifiers [] = 'sql.com'; $arrayIdentifiers [] = 'mylogin'; $arrayIdentifiers [] = 'myPassword'; $arrayIdentifiers [] = 'MyDatabase';
return $arrayIdentifiers;
}
?>
Calling a function
So far we declared functions but we did not use them. This is what we are going to study now with the function call.
Calling a function is done in the main program after you declare the function. A function is called by his name followed by the parameters. Let our first function that calculates the sum of two numbers and displays the result on standard output. The call is carried out as follows:
Call the procedure to Sumcalculate()
<?php function Sumcalculate ($a, $b) { // Declare the local variable $ sum $sum = $a + $b; // Display result echo 'The sum of ', $a , ' and ' , $b , ' is ' , $sum; } Sumcalculate(10,1); echo '<br/>'; Sumcalculate(7, 23); echo '<br/>'; Sumcalculate(130, 231); echo '<br/>'; Sumcalculate(98, 62); echo '<br/>'; ?>
After completing the 4 functions, the product result is the following:
Outturn calls to Sumcalculate ()
The sum of 10 and 1 is 11
The sum of 7 and 23 is 30
The sum of 130 and 231 is 361
The sum of 98 and 62 is 160
Let us now see what happens with the same function that returns the value. The one with the return statement. By running the above code , we notice that nothing appears when the execution took place as planned. What for ? Simply becaufe the returned values were not retrieved and stored in data structures (variables, array, object …). We will store them in an array called $ resultsSum before displaying the contents of it.
Example salvage value returned by the function calculating Sum ()
<? php / ** * Here the function was declared * /
// Declare the array
$ resultsSum = array ();
$resultsSum [] = Sumcalculate (10,1);
$resultsSum [] = Sumcalculate (7, 23);
$resultsSum [] = Sumcalculate (130, 231);
$resultsSum [] = Sumcalculate (98, 62);
// Display the contents of the table
echo ‘<pre>’;
print_r ($ resultsSum);
echo ‘</ pre>’;
?>
This produces the following result:
Result of the script
Array
(
[0] => 11
[1] => 30
[2] => 361
[3] => 160
)
So always think about the record / return values in a variable / table, or use it directly in a condition.
Visibility variable
When a variable is declared, its visibility in the main program depends on its context. PHP there are 3 levels of visibility described below:
The superglobals: these are in fact the tables like $ _SESSION, $ _COOKIE, $ _GET, $_POST, $ _SERVER … There are created by PHP and are accessible (read and write) from anywhere in the program. They can therefore be called within a function without being passed as a parameter thereof.
Global variables: These are all variables, arrays, objects, and constants we create ourselves in the main program. These data structures are visible in theory than in the main program but it is possible to have access in a function without the parameter.
Local variables: These are all variables of a function (including parameters). Their visibility is only local, that is to say in the function itself. The main program therefore can not act on these variables. This is also why their name may be completely arbitrarily chosen without confusion for PHP with global variables of the main program. They are automatically deleted from memory when the function has been completely executed.
If we try to call a variable that is not in the right context, the PHP interpreter will return a type error Notice: Undefined variable: myName in /Applications/htdocs/Tests-PHP/filename.php on line 8
Scope of a variable
We have seen that global variables declared in the main program and local variables declared inside of a function can not be accessed. The two spaces are completely closed and independent. In PHP there are 3 levels of scope of a variable that is global, local and static. The last one is a little special.
A variable declared in function and prefixed with the global keyword is considered global. It then becomes visible in the function but also outside thereof.
Traditionally a declared variable in the function defaults to a local scope. It is visible only in the function and is destroyed at the end of its execution.
A variable declared in function and prefixed with the static keyword is considered a local variable whose value is preserved throughout the execution of the main program. This value can then be reused by calling the function new time.
Illustrate the first and third points using a common example. The following function simulates filling a car fuel. The fuel budget is a global variable decremented amount of refueling.
Illustrative examples of the scope of variables in a function
<?php // Declare Function function fillingPetrol ($volume, $PricesAtLitre) { // Variable Declaration global $Gasolineoverallbudget; static $GasolineTotalVolume ; $amount = 0;
// Calculate the filling of petrol
$amount = round ($volume * $PricesAtLitre , 2);
// Withdrawal $amount $Gasolineoverallbudget
$Gasolineoverallbudget -= $amount;
// Add the volume to the total volume recorded
$GasolineTotalVolume += $volume;
// Display information
echo ‘You put ‘, $volume, ‘ L gasoline <br />’;
echo ‘Litre Price :’, $PricesAtLitre, ‘ euro <br /> ‘;
echo ‘Total Price :’, $amount, ‘ euros. <br />’;
echo ‘Gasoline Budget remaining : ‘, $Gasolineoverallbudget, ‘ euro. <br />’;
echo ‘Total gasoline Volume\’s from the beginning :’, $GasolineTotalVolume, ‘ L <br />’;
}
// Global variables Declaration
$Gasolineoverallbudget = 700;
// First Refueling
fillingPetrol (42, 1.25);
// Second Refueling
fillingPetrol (38, 1.19);
// Third Refueling
fillingPetrol (43, 1.23);
?>
The result after execution of the program is:
Result of program execution
You put 42 L gasoline
Litre Price :1.25 euro
Total Price :52.5 euros.
Gasoline Budget remaining : 647.5 euro.
Total gasoline Volume’s from the beginning :42 L
You put 38 L gasoline
Litre Price :1.19 euro
Total Price :45.22 euros.
Gasoline Budget remaining : 602.28 euro.
Total gasoline Volume’s from the beginning :80 L
You put 43 L gasoline
Litre Price :1.23 euro
Total Price :52.89 euros.
Gasoline Budget remaining : 549.39 euro.
Total gasoline Volume’s from the beginning :123 L
Explanation: The variable $Gasolineoverallbudget declared global in the function. This means that it is accessible for reading and writing in the function but also outside thereof. The variable $GasolineTotalVolume is declared static. The variable $amount is a useful local variable only during the execution of the function. It is destroyed when the function is completely executed. It counts the total volume of gasoline purchased from the beginning. Its value is retained for subsequent calls to the function. The native function round () rounds the sum of refueling two decimal places. The following calculation step uses arithmetic operators combined. More information about the tutorial of PHP operators.
Parameter passing by reference or copy
We begin the penultimate important functions for users. This is the parameter passing (which we have already seen in the function calls). There are two types of parameter passing in PHP. This is the passage through copying or passing by reference.
In the first case, the value passed in parameter of the function is unchanged. In fact the function works on a copy of that value. This is also the default parameter passing PHP. Here is a simple example that shows the mechanism:
Presentation of the passing mechanism by value
<?php function multiplyByTwo ($number) { $number *= 2; }
$aNumber = 5;
multiplyByTwo ($aNumber);
echo $aNumber; // Show 5
?>
To change the value of $aNumber, proceed to a pass by reference. The passage by reference is to pass the memory address of the variable, not a copy of its value. To do this, simply add the & symbol before the setting in the function signature. Returning to our previous example:
Presentation of reference by passing mechanism
<?php function multiplyByTwo (& $number) { $number *= 2; }
$aNumber = 5;
multiplyByTwo ($aNumber);
echo $aNumber; // Display 10
?>
Note: The objects are always passed by reference. The passage by copying does not apply to these data structures.
It is also possible to return by reference but it was not much interest since in general we refer the value of a local variable we then store in a global variable in the main program. In some special cases, it may be interesting. To report back by reference to the value, we must place the & symbol before the name of the function in his statement.
The functions in infinite settings
PHP also allows you to create features in infinite settings. This is what the following example illustrates.
Example of a declaration and function call parameters infinite
<?php function HavingPortraitRobot () { // Storage parameters in a table $info = func_get_args(); // Display information echo 'The suspect robot portrait ' , func_num_args () , ' criteria'; foreach ($info as $element) { echo ' - ', $element, ' '; } }
HavingPortraitRobot
(
‘Man ‘,
‘blue eyes’,
‘brown’,
‘hair cut short’,
‘185cm’,
‘hooked nose’,
‘scarred left cheek’
);
?>
Note that we declare a function without parameters. The result of the execution of the previous code is the following:
Result of program execution
The composite sketch of the suspect has seven criteria:
man
blue eyes
brown
hair cut short
185cm
hooked nose
scarred left cheek