Today I am going to share how to make or declare a function in PHP. Declaring a function is not so critical. We create function to use it repeatedly. There are many advantages of using function. We will learn that by creating lots of function one by one. Now let's start to know what is function, how to declare it and what is the necessary of that.
Function:
A function is block of statements that we can use in our program as much as we need and as long as we need. There are many built in functions in PHP. But we will learn how to create or declare user defined functions.
Function Signature: In function signature there are four things that we should follow. These are: the 'function' keyword, function name, function parameters and the infamous curly brace. Now we will learn what they are and how they looks like.
| Very simple example of declaring a function. |
2. Function Name: After placing the 'function' keyword just give one space (or more if you like but that is not a standard way) and put the function name. We can start with underscore or any alphabet and digit like A-Z or a-z or _A-Z or _a-z or _0-9. Don't use any digit at beginning of a function name. But It is better to put the function name relevant to the function's responsibility.
3. Parameter: Parameters are sometimes called argument. So don't worry about this mixture. There is a technical difference between argument and parameter but you don't need to worry about that for now. I will discuss about that later. This can contain multiple parameter. In this signature we have to place those variable that are needed in our code to get the result. This parameter is like inputting something in a code. For example: ($arr, $str, $p etc.).
4. Curly Brace: A function starts with opening curly brace( { ) and ends with closing curly brace( } ). Under this brace we have to create code to get the result. In this field we can make any instruction to get our result. In PHP, We can print our result by "echo" statement or using "return statement" inside the statement. If we don't put one of them we don't get any result when we call the function.We should remember that, when a php function get "return statement" it will never run any code after that. It will just give the result before the return statement. I will discuss later while I will start coding.
After completing these we have to call the function . To call a function we have to place the function name and after that place the value of the parameter.
Now I show you how to call a function. I call the function that I created at the top.
myfunction(); we must put value[$input] of the parameter that is relevant to the code.
This is way of calling a function. It can be called in variable, any where we can call that in our code. We can also echo it directly. We will learn it by coding.
Comments
Post a Comment