About MeMiscellaneousGeek StuffSkydiving |
Geek Stuff : Tutorials : PHP : Basic Functions with PHPTo avoid littering your web pages with lots of PHP code for common things you will need to do in more than one page it is often convenient to create a function that you can just include and call in any page that needs it. Creating a PHP function is easy to do, and will be good practice for when you get into Object Oriented Programming and start using them as methods in classes. In this tutorial we will be creating a very basic function that takes 2 "arguments" (values supplied to a function when it's called) and returns a variable with the result after the function code runs. <?php // basic function that calculates the sum of 2 numbers function addNums( $firstNum, $secondNum ) { // calculate the sum of the 2 sumbitted arguments $sum = $firstNum + $secondNum; // then we return the value after function code has run return $sum; } ?> If we save this function in our /includes directory as "function_addNums.php" we can include it any page where we need to add two numbers and call the function as needed. To include our function in a web page we can place the following code somewhere near the top of the page. I usually include any functions I need before anything else in the page at the top. <?php
// include addNums() function
include($_SERVER['DOCUMENT_ROOT'] . "/includes/function_addNums.php");
?>
Then later in the page when we need to add two numbers together we can just call our included function and give it two numbers we want added together. <?php /* create a couple of variables and assign a number to each * (you could also just hard code numbers in the function arguments) */ $numOne = 4; $numTwo = 8; // call addNums() function and give it two numbers to add together $sum = addNums( $numOne, $numTwo ); // then you can print out the sum anywhere you want echo $sum; ?> The above code would print out "12" wherever we echo'd the $sum variable. Functions are a handy thing. They are considered "procedural" programming, which I still use quite a bit. For smaller sites and web applications procedural programming works well. I hope this tutorial helps you in your web development! |
|
| ©1995 - 2008 Tim Patterson, All Rights Reserved (Unless otherwise noted) | ||