As with any decent language, PHP allows you to write your own functions. Let's look at a simple one.
As you can see the name of the function fits. We declare a function by typing, of all things "function", followed by a space, and then the name of the function followed by two brackets, you may have noticed this by now, all functions have these two brackets, for passing parameters. In this case we aren't using any. Then we put the code we want to execute between the two curly braces, this is a function. To call this function we would just call it's name.
Which would print out "This function prints a string". It executes the code between the curly braces. A function can contain any valid PHP code, even other functions. This may seem pointless, but read on, allow me to elaborate.
Whether you call them parameters or arguments, they're the same thing. A parameter is a value that you can pass to a function and use inside the function. Let's write an example.
Now when we call this function, we can include a parameter, the value included as a parameter will then be handled, within the function, as $text, so say we do:
The contents in $string will then be passed to the function, where they will be handled as $text. In this case we just print it out. We could use two parameters:
In the above example, if you then tried to work with the variable $sum outside of the function you'd get a shock. The variable $sum does not exist outside of the function. We can change this:
We do this by making the variable $sum a "global" variable. To do this we simply state global $sum;. Now $sum is accessible from anywhere in the script, it's not just a variable private within the function. If we didn't define this variable as global, when we tried to print it out after the function call, it wouldn't work.
A function is useful when we want to perform the same actions over and over again. Let us imagine we have written a script that allows a user to post a message on a "guestbook". Yet we don't want to allow them to use HTML in their post, in their name, or in the subject of their post.
Now this function will take our argument, if it contains any HTML (anything surrounded by < and > , it will take it out of the string. The return $stripee; at the bottom of the function tells the function to return the new value of $stripee to us.
Now we don't want any HTML in the user's posts, maybe we don't trust them, we don't want them to be able to mess around with our page's HTML, so we use the function we have written to clean up:
Send each variable to the function as a parameter, let the function clean out any HTML, and then return the new value of the string to the same variable name. So now any HTML would be gone:
Using functions makes things alot easier, you can put all your functions in a separate file and just include() them into your script.
No Comments for this page.