|
Page 1 of 5 Functions
The real power of PHP comes from its functions. In PHP - there are more than 700 built-in functions available. In this article we will show you how to create your own functions.
As your code gets longer, being able to create your own functions is an essential step because it breaks up that code into manageable sections. As you know, functions are sets of statements that can be called by name, which means that they're ideal for packaging your code into manageable chunks. When your scripts get longer than two-dozen statements or so, you should consider breaking up things into functions.
Creating functions also facilitates script development, if you've got a problem in a script that is 2,000 lines long, imagine how hard it will be to find that error. But if you've broken up your code into functions, each of which is only two-dozen lines or so, it'll be much easier and when you know that a given function works as it should, you don't have to worry about it anymore.
Breaking up scripts as they get longer is also a good idea in terms of scope. Scope is the visibility of an item, such as a variable, in your script for example, if you have a 2,000 line script, and you use a variable named $counter at the beginning, but then you forget that you've done so and use another variable with the same name near the end of the script, they're actually the same variable. Thus, you have an unintentional conflict because when you use $counter in one place, it'll set its value everywhere.
Restricting code to functions helps solve this unintentional problem, the variables you use in a function can be restricted to the scope of that function. Thus, you don't have to worry about those variables overlapping other variables with the same name by mistake, they cannot escape the scope of the function.
How do you create your own function? Here's how to do it formally:
function function_name([argument_list...]) { [statements;] [return return_value;] }
|