| Home > Computer & I'net > Basic and Not so Basic "Fun... |
|
|
|||||||||||||||
|
|
|||||||||||||||
|
||||||||||||||||
Basic and Not so Basic "Function" Features Using PHP | |
Okay for those of you who are new to PHP we will go over the basics first. What is a function? A function is a way to encapsulate a set of code. In other programming languages functions are sometimes referred to as methods or procedures. As well some languages even make distinction between procedures and functions. In PHP there are just functions, though with object oriented programming the function in the class are sometimes referred to as methods to be consistent with OO terminology, lets save that for another article. The following reasons why one would want to use functions are: Code Reuse, for example you want to calculate the salary for several employees you could reuse the same calculation for each every employee with out re-coding it Easier code maintenance, using the last example, it is a lot easier to update or fix bugs in one place rather then change the same code in several different places. This also lessons the chance of you making a mistake in one or more those different places with the same code. Makes your code a lot more modular and therefore a lot more readable instead of one huge giant program or script from top to bottom. Take a look at the following code, mind you it isn't entirely correct but you should get the point: employees = getEmployees(); You can see from here things are broken into 3 basic parts getEmployees, calculateSalary and showReports. All three are self-explanatory and moreover easier to read and understand. Okay now that we know why to use functions what makes up a function, this is best illustrated by simple HelloWorld code. function helloWorld() { To use the sample code all you have to do is call the function name helloWorld(), in this case there are no parameters. The next example includes one parameter where you pass in the words to be printed: function helloWorld($yourWords) { The function now needs to be called with a parameter, you simply call the function with correct parameter(s), in this case it would be helloWorld("Hello World"). Yes a function can accept a number of parameters, for example helloWorld("Hello","World"), of course the function needs to be defined to accept the correct number of parameters. If you want the function to return a value all you have to do is include the return statement in your function, take for example you want the helloWorld to return a response. function helloWorld($yourWords) { OR function helloWorld($yourWords="GoodBye") { OR function helloWorld($time) { In this last example we changed it a little to demonstrate you can call functions within functions as well you can have multiple return statements however only one will ever be returned based on the condition statements. In all cases only one value can be returned from a function. In the second example you will notice function helloWorld($yourWords="Good Bye") assigns a value for $yourWords, this called default assignment. If the function helloWorld is called without parameters then $yourWords by default will be assigned the value "Good Bye". Another feature functions are capable of is the ability to access global variables, for example $globalVariableHello = "Hello World"; It is recommended not to use global variables and or multiple return statements. It will save you a lot of hours of debugging. The rule thumb is one entry point and one exit point. An alternative to multiple exit points is simply use a variable: function helloWorld($time) { An alternative to global variables when you want to maintain the value within a function is to use static variables: function counter() { Output: 0 1 2 The static variable value is retained even after the execution of the function is complete, as you can see in the above example $count is incremented each time it is called. Going Beyond the Basics Returning More then One Value Previously it was mentioned a function couldn't return more then one value. This is still true but there is a way to do indeed return more then one value. Simply make the return value an array. This is especially useful when your web application is broken up into layers/tiers and you want to be able to pass the error/exception from a lower tier to the top, so the user gets a more user-friendly error message. An example: function db_update_user_info($dbConnection,$userInfo) { You can see this function db_update_user_info returns more then one value, this example is for illustration purposes. You may want to clean it up, for example you may want to use string for index names and the error messages and successful results could actually share index 1, $result[1], rather then create 3 indexes. Pass By Reference This is not really an advance feature but rather an understanding of what kind of parameter is being passed in. By default passing in parameters to a function it is passed in by value meaning a copy of that variable is passed in. If manipulation is done to that copy (inside the function) the original variable outside the function retains the same value assuming no code outside the function updated it. Your other option is to pass in variables by reference this is indicated by the ampere sign symbol, &. Meaning if the function does updates to the variable it affects the original variable outside the function. This is because the function is not accessing a copy of the variable rather the address of where the original variable resides. An example passing in by value: $theVar = "hello world" Output: hello world An example passing in by reference: $theVar = "hello world" Output: good bye Dynamic Functions To create a function based on a condition. This is better explained with an example: Example 1: $theVar = 1; Output: Hello World 1 Example 2: $theVar = 2; Output: Hello World 2 The implementation of helloWorld function is created based on the value in $theValue, it is as simple as that. Another way to dynamically create a function is to create an anonymous function a function without a name: $anonymousFunction = create_function('$arg1,$arg2','echo $arg1 . " " . $arg2;'); Output: Hello World This may seem a little confusing at first because the function doesn't have name, instead the created function gets assigned to a variable, from there you use the variable directly as if it was the function. Variable Indirect Function $process_function = "helloWorld"; Output: Hello There Now to do a variable indirect function call look at the following code first: $menuOption = 2; Output: Option 2
$menuOption = 2; Output: Option 2 Notice process_option$menuOption is the function name but name itself is contains a variable. Depending on what the variable is the called $process_function will call the appropriate function assuming that function indeed exists. ----------------- Jason is a wireless and open source developer enthusiast who enjoys creating synergy and sharing knowledge in the software development world. To learn more about him visit his personal site at http://www3.telus.net/jasonlam604/ | |
| Articles |
•Auto & Trucks•Business•Computer & I'net·General·Apache·CSS·Database·Hardware·HTML·Javascript&DHTML·Linux·MySQL·Operating System·Perl / CGIPHP·Programming·Publishing·Search Engines·Software Problems·SSI·Tips & Tricks·Utilities·Web Design•Family•Food & Drink•Gardening•Health•Other•Pets•Psychology•Spiritual•Travel•Women |
| Calculators |
|