|
|
|---|
Declaring a FunctionLet's begin with the general syntax/form of a function:
<?phpSome rules about function names are that a valid function name will always begin with a letter or an underscore and may follow with any number of letters or numbers. You should try to use a function name which is most relevant to what it is meant to do. For example, if your function will calculate difference between two given numbers, then a function name of "diff_numbers" is more appropriate than "my_function". Isn't it? But you are free to use whatever name you want to assign to your functions as long as it helps. You can use functions in variety of ways. Some other ways of using functions are as mentioned below: Calling a function inside another function:
<?phpYou must have notices that a function which was inside another function was called from outside. That is possible because in PHP all functions are global functions and can be called from outside the function as well. Calling a function based on conditions:
<?phpIn the above example the condition is evaluated first and if found true then a call to function print_true() is made, else if the condition evaluates to false, a call to the function print_false() is made. Now, we will learn to pass arguments to a function in PHP. It is much simpler than what you think. Here is a basic example to begin with:
<?phpIn the above example, we first declared a function called print_input() and an aurgument of $input. When you want to pass a value to that argument, all you have to do is call that function and pass a value into it as we did by calling it print_input(5). The arguments are comma seperated values, so if you want to use more arguments for the same function, it will look somewhat like this:
<?phpIn the above example, notice that we have added one more argument to the function, $input_a. This allows us to pass two arguments to the function when we call it, such as - print_input(5,6). You can increase the number of arguments to the argument's list and use it accordingly. |
|
|
|---|