PHP Functions with Parameters
For the most part a function is completely self-contained. It can neither receive, nor give information to the rest of your program. In some ways functions are a little like solitary confinement in prison. The only way that the prisoner may receive food is if it is slipped under the door as a parameter (we'll ignore the problem of dirty dishes for now).
Passing information to a function allows us to manipulate the function so that it can apply to more than one situation (or receive different kinds of meals like breakfast, lunch and dinner). Using the PHP date printing example, we can modify our PHP function so that it can print any date format we choose, instead of only one.
Creating the Function
Using the same structure as a basic function, add a single variable to the parameter brackets on the first line. If you want to add more than one parameter, use a comma to separate each variable.
function printDate ($dateformat) {
$today = date($dateformat);
print $today;
}
To use each parameter from within the function, use the variable name that you defined in the parameter brackets. In this case it is $dateformat. You can use the parameter as many times as you'd like within the function. You may want to print out a statement like:
print "Today's date is $today. It has been formatted according to $dateformat";
Calling the Function
The function is called from the page at the point where the value
should be printed, like this:
<?PHP printDate("Y-m-d"); ?>
Each parameter must be present when the function is called, but it does not need to have a value. The printDate function is expecting only one parameter $dateformat. You can pass an empty parameter by putting two quotes together: printDate("").
Activity
Use the basic function above to print a date to the page using a flexible date format.
- Create a new XHTML page.
- Add the function provided with one parameter to the very top of your
page, inside the PHP tags. - From the HTML of your page, call the PHP function.
- Test your function (upload it to the server, and load the page in a web browser).
- Use the function again to print additional dates to your page with the following structures:
- Tuesday November 30, 2004
- 2004-01-01
- December 1, 2004
- 23/1/2005
Want More Tutorials?
Are you interested in getting even more tutorials sent to your inbox? Sign up for our incredibly popular tips mailing list and get a free tutorial every month. You may even win a coupon for a free e-book (include your whole name if you want to win stuff).
For a limited time we'll even send you a bonus tips sheet The Top Ten Mistakes People Make when Theming Drupal when you sign up for the list.
