User defined functions are those php functions that are created or defined by users.
function functionName(){
line of codes......
}
functionName();
The function needs to be called outside of the function block to be executed.
function printText(){
echo 'Hello World!';
}
printText();
Value(argument/s) can be passed in a function.
function functionName($args){
}
While creating user defined functions, we might accidentally create same named function. To avoid such errors, we can check if a function already exists using php inbuilt function_exists() function that returns a boolean result.
if(!function_exists(sum)){
function sum($a,$b){
$sum = $a+$b;
echo $sum;
}
}
sum(10,20);
Printing values inside a function is a bad practice. So, we return value from such functions rather than printing it there.
function sum($a,$b){
$sum = $a+$b;
return $sum;
}
Variables declared within a function can't be directly called outside so we need to store it in another variable and print it separately.
function sumsub($a,$b){
$sum = $a+$b;
$sub = $a-$b;
return [$sum,$sub];
}
$x = sumsub(10,5);
echo 'the sum is '.$x[0];
echo 'the sub is '.$x[1];
Variables if defined inside a function can only be accessed within the scope of that function. Such variables are called variables with local scope.
function a(){
$x = 20;
}
echo $x // is invalid.
Variables if defined globally i.e. outside a function can be accessed everywhere within the sript. Such variables are called variable with global scope.
$a = 20; echo $a;
If a global variable needs to be called inside a function it needs to be defined as global in that function.
function b(){
global $a;
$a++;
}
b();
echo $a;
Static variable preserves the last value stored in it and executes the function.
function a(){
$a = 1;
$a++;
return $a;
}
echo a();
echo a();
echo a();
Result 222
function a(){
static $a = 1;
$a++;
return $a;
}
echo a();
echo a();
echo a();
Result 234
function check($a){
$a++;
}
$b=10;
check($b);
echo $b;
Result: 10
function check(&$a){
$a++;
}
$b=10;
check($b);
echo $b;
Result: 11
Leave a comment