![]() |
|
PHP user defined functions. Free online PHP and MySQL Web Database Programming Tutorial... |
| Lessons | PHP User Defined Functions 1 |
|
|
In simple words a function is a named block of code that can be executed whenever we need, again and again. All functions start with the word "function()". Function names can start with a letter or an underscore but not with a number. The block of code has to be enclosed between { and }. Example A simple function that prints "Hello World": <html> <body> <?php function printHW() { echo "Hello World"; } printVar(); //this is how we call functions in PHP ?> </body> </html> The above was a very simple example of a user defined function. The function in above example does not take any argument and does not return a value. We can define a function that takes arguments and returns a value. Consider the following example: <?php function func($arg_1, $arg_2, ..., $arg_n) { echo "Example function.\n"; return $retVal; } ?> PHP also allows functions to be defined inside functions. This is a rare concept and is not found in many programming languages. The following example shows this concept: <?php function func() { function func2() { echo "I don't exist until func() is called.\n"; } } /* We can't call func2() yet since it doesn't exist. */ func(); /* Now we can call func2(), func()'s processesing has made it accessible. */ func2(); // this is valid now. ?> PHP also supports recursive functions: <?php function recursive($val) { if ($val < 10) { echo "$a\n"; recursive($val + 1); } } ?>
Next: PHP Defining Functions 2
|