Our original intention was to make PHP's user-defined functions clearer via a simple calculator function, one which accepted two numbers and added, subtracted, multiplied and divided them. How boring! How about, instead, if we create a calculator, one which accepts two numbers and performs mathematical operations on them? How about if we add a twist by claiming this calculator to be the one Alice would carry on her journey through Wonderland (assuming she needed one)? And how about if we substantiate that claim by adding the Wonderland factor, a random number that skews the results of your calculations so that they're never correct? Each time you reload the page, you should get a different answer - that's the random number at work!{mospagebreak title= Coding For The Unexpected} So far, all the functions you've seen accept a fixed set of arguments. However, you might often find yourself in a situation where you're not quite sure of how many arguments you will be passing. In the old days of PHP3, you had no choice but to grin and bear it. However, PHP4 allows you to create functions which will accept any number of arguments, regardless of whether or not they've been defined in the function definition. There are two PHP functions that add this functionality: func_num_args(), which returns the number of variables passed to the function, and func_get_args(), which lets you obtain those variables in the form of an array. Our next example will make this clearer. And here's the output: And that's about it for this issue of PHP 101. You should now know enough to begin writing PHP code for your Web site. We'll continue to bring you tutorials on other aspects of the language - tell us what you'd like to read about! And until next time...stay healthy!
blog comments powered by Disqus |