The real powers of the php comes with the functions.There are thousands of built-in functions in php .
Generally the functions are of two types.
1 . Built-in functions : The built-in function are those functions which comes with php itself , such as echo() , print() …
2 User Defined functions : The user defined functions are those functions which can be defined by the users themselves and can be re-used with in the programs .
Rules to declare a function :
- First , It starts with the Access Modifiers , such as public , private , protected etc
- If there exist no Access Modifiers it will be treated as the public .
- Secondly , Add the function name
- The function name should start with either alphabet or underscore (_) , not a number or any special characters .
- With the curly bracket to start and end the bunch of codes .
- Finally call the function to execute .
Note : To know more about PHP Access Modifiers click Here .
Syntax for user-defined functions :
public function functionName() {
#Block of code
}
functionName() //calling the function
Example :
<?php
function php_function() {
echo “Starting with the php functions !”;
}
php_function(); // call the function
?>
Output :
Starting with the php functions !
PHP Function with Arguments :
- The information is passed to the function via arguments , the the arguments are the values passed to in to the function to perform its operations .
- The arguments are just like a variables .
- The arguments are passed in to function inside the parentheses .
- The multiple arguments can be passed on to the function as comma separated , Ex : functionName( argument1 , argument2 , argument3 ,…….).
- Arguments assigned with equals to ( = ) are called the default arguments , if we don’t pass any argument to the function it will automatically the the default argument .
Study is Boaring .
Playing is good for health .
Time is Everything .
Here , From the above example you can see the last function call doesn’t have the second argument and the default argument is assigned to it .
PHP Function with Returning values .
In order to return the value from the function you need to use “return” statement.
Let’s see the return statement from the above example :
<?php
function learn($course, $res=’Every thing’) {
return “$course is $res . <br>”;
}
echo learn(“PHP”, “Interesting”);
echo learn(“Study”, “Boaring”);
echo learn(“Playing”, “good for health”);
echo learn(“Time”);
?>
Study is Boaring .
Playing is good for health .
Time is Everything .
Note : After returning the value , to print the output you need to print the statement with echo or print etc …