PHP Helper Functions
When developers create applications and scripts in programming languages, the process can be an intense and demanding one. For this reason, programmers commonly look for ways to minimize the amount of code that an application requires and to re-use code where possible. Web programmers can use PHP functions for this purpose. In addition to providing the means to re-use code, using functions makes a script easier to update and maintain.
-
Declaration
-
PHP scripts can include functions by listing their names, parameters and implementation details. The following sample code could appear within a PHP script:
function do_something() {
echo "Doing something";
}
When a function declaration appears within a PHP script, other code can make use of the processing provided by the function. PHP developers can create helper functions to provide functionality that they need to use once or more within an application. If a function is called from multiple locations, it only needs to be updated or maintained within the function declaration and any changes will be reflected throughout the script.
Calls
-
Once a PHP script has access to a function, code can call it using its name, as in the following sample syntax excerpt:
do_something();
When this line appears within a script and the script then executes, the content of the function called will execute, whatever it happens to be. The "customer" code calling the method does not even need to have any awareness of the content of the function, as long as its general purpose is clear. For this reason, developers often include informative comments next to helper functions:
//write something to the browser
This is a simple example, but in general a helper function will be more useful if it is listed along with a detailed comment.
-
Parameters
-
PHP functions can accept arguments, sometimes referred to as parameters. Any parameters appear within the function declaration as in the following example code:
function output_text($the_text){
echo "<p>".$the_text."</p>";
}
Customer code can call this method, passing it a string parameter as follows:
$some_text = "Hello";
output_text($some_text);
This code will cause the passed string parameter to be output according to the function implementation.
Returns
-
PHP functions can return variables and values to the code calling them. The following sample code demonstrates declaring a trivial function with a numerical return value:
function multiply_it($num){
return $num*3;
}
External code can call this function, passing it a parameter and receiving the returned value as follows:
$my_num = 5;
$new_num = multiply_it($my_num);
The new number variable should now contain the value resulting from the multiplication operation defined within the function declaration.
-
References
Resources
- Photo Credit Comstock/Comstock/Getty Images