Introduction to Functions
Real power of PHP Comes from it’s bult-in functions, which are more then 1000.
PHP User-defined Functions
- A function is a block of statements which can be used many times in a program.
- A function will not execute until you will call.
- A function will not execute on page load until you will call.
User Defined Function Syntax
<?php
function functionname(){
//code goes here.
//.
//.
//.
}
?>
Function Example
<?php
function Welcome(){
echo 'Welcome to PHPDocs.com';
}
Welcome(); //calling the function
?>
Function with Parameters Example
<?php
function Sum($value1,$value2){
echo $value1+$value2;
echo "<br />";
}
Sum(20,30); //it will show 50
Sum(30,50); //it will show 80
Sum(40,60); //it will show 100
?>
Function with Return Example
<?php
function Multiply($value1,$value2){
return $value1*$value2;
}
echo Multiply(2,5)."<br />; //it will show 10
echo Multiply(3,6)."<br />; //it will show 18
echo Multiply(4,8)."<br />; //it will show 32
?>
Function Parameters By Reference Example
To allow a function to modify its arguments, they must be passed by reference
place the & sign in the start of paraemeter to get Parameter by Ref
<?php
function Increment(&$value){
++$Value
}
$counter=0;
Increment($counter); //it will show 1
Increment($counter); //it will show 2
Increment($counter); //it will show 3
Increment($counter); //it will show 4
?>