Web Design/Dynamic Websites/Simple Functions in PHP
Appearance
Web Design → Simple Functions in PHP
|
Note: Work in progress PHP.net has a reference on PHP functions, but it's a little complicated for your average beginner.
Example PHP file with function
[edit | edit source]Try testing the following PHP file:
<?php // // A simple function that prints a welcome message // function welcome() { print("<h2>Hi there. Welcome to PHP functions</h2>"); print("<p>Here we'll learn a little about functions</p>"); } welcome(); welcome(); welcome(); ?>
Can you explain why it does what it does?
Example 2: a function with an argument
[edit | edit source]A small modification:
<?php // // A simple function that prints a welcome message // function welcome($username) { print("<h2>Hi there $username. Welcome to PHP functions</h2>"); print("<p>Here we'll learn a little about functions</p>"); } welcome("Michael"); welcome("Izaak"); welcome("Brigitte"); ?>
Can you explain what's happening this time?
Example 3: Something more useful
[edit | edit source]So far we've done simple PHP templating using include files. But we can replace this with functions to, and give ourselves some extra power while we're at it! Try the following:
<?php // // A simple function that prints the code that's at the // beginning of every page on my site. // function printHeader() { ?> <html> <head> <title>Home page of my site</title> </head> <body> <h1> My website </h1> <div id="main"> <?php } printHeader(); print("<p> The content of my page would go here</p>"); // printFooter(); // woops, we don't have this function yet! ?>
Again, test out this page and then see if you can explain what it's doing!
Here's the challenge:
- See if you can modify your printHeader() function so that you can say: printHeader("Page 2"); - and the text "Page 2" will be displayed in the title tags (look back to a previous example!)
- Try creating and using your own printFooter() function.
Of course, we'd remove these functions into an include-file so that we can reuse them on other pages!