Functions
Despite the fact that PHP comes with such a large selection of functions to perform all sorts of tasks, you will want to create your own functions when the need arises. If you find yourself doing the same thing repeatedly, or you want to share code across projects, user functions are for you.
Writing monolithic programs—code that starts at the beginning and runs straight through to the end—is considered very bad for program maintainability, as you are not able to reuse code. By writing functions, you make your code shorter, easier to control and maintain, and less prone to bugs.
A Simple User Function
You can give your functions whatever name you like; they follow the same guidelines (without the $) as PHP's variables. You may not redefine PHP's built-in functions, and care should be taken to ensure that your function names do not collide with existing PHP functions—just because you don't have the imagepng()
function available, it doesn't mean others also won't.
The simplest user function in PHP looks something like this:
function foo() {
return
1;
}
print foo();You define your functions with the function keyword, followed by the name of the function and two parentheses. The actual code your function will execute lies between braces—in our example function $foo, our sole line of code is return 1; we will get to that in a moment.
After the function definition, we can treat foo() like any other function, as seen in line four where we print out the value it returns (known as ...