The Role of PHP Functions

Sep 20, 2007 18:26 GMT  ·  By

You can extend the PHP capabilities by defining your own functions. When you use functions, certain actions of your codes could be repeated in different programs. You can save time by defining a function that gives an output needed in many cases, such us the CSS (cascading style sheets) structure of a web page managed by a PHP function.

Besides the increased speed of programming tasks, there is another advantage. You can use a certain function inside a script as many times as you need, in this way the code being optimized for speed and accuracy. The name of the function is also important for the work flow of the code. You should use specific names that will point out the function actions in order to easily refer to it, if your program becomes complex. For example, let's consider the case when you need to automate a task of solving a linear equation of type ax+b=0, with x being the root and a,b the polynomial coefficients:

code
My First PHP Equation Solver
All PHP functions will begin with the keyword function, followed by its name and parameters. In this case the parameters are a and b, which are variables, denoted by the $ sign. When the function is called (in the line 9 for this script), it will output the root of the equation ax+b = 0. The PHP built in function echo is used to call the function solve and to display its output. In this case, 5x+5 = 0, the script will display -1 as the root of this simple equation. Save this code in a text file as solver.php for example, then run it from an Apache web server PHP enabled and change the equation coefficients to solve your own linear equations in a single unknown variable.

In the solve function presented here, the return keyword tells the function solve to output the value of the polynomial equation root. This is a simple example, but functions could be more productive if you give them a universal character. For example, you can implement a numerical recipe in a function for solving an equation with more unknowns, as the case of higher order polynomials.

The best practice is to use simple algorithms for the function definition in order to obtain the desired performance. You can also employ PHP to solve systems of equations, but in this case the code should be adapted strictly to the given problem, because there is not a universal code to solve all problems and in the same time to have an optimal performance. The idea is to minimize the variables or function calls by choosing the right programming algorithm, which will give you benefits in code portability and performance.