Hi again, please enjoy the second part of our PHP Development guide for beginners. This part is dedicated to functions.
Functions are small pieces of code, that perform a calculation, check or anything you want. The reason why these pieces of code are made available as functions, is so you can re-use the same functionality again and again, without reprogramming the same thing over and over. Consider a simple example: You want to display the following text for each user logged in to your website: “You are from England”, where England is a variable depending on the individual user. In that case, you could consider a function like this:
function write_country($country_name) { return 'You are from '.$country_name; } echo write_country('England');
You can use functions for various purposes. One of the most important concepts for functions is the return value. The return value makes it easy for you to continue your operation with the given result. The above example simply return the text string you want to display. It could also be something more advanced. Consider the following example:
function is_greater_than($number, $limit) { if ($number > $limit) { return true; } else { return false; } } $a = 10; $b = 5; if (is_creater_than($a, $b)) { $a.' is greater than '.$b; } else { $a.' is NOT greater than '.$b; }
You can use functions in many ways. In general you should never program the same thing twice. So if you need to reuse some code somewhere, make a functions. In a chapter further down the road, I will discuss how you can bundle functions in so-called classes in object oriented programming. But for now, play with functions :-)
No comments yet (leave a comment)