php user defined functions

User defined functions are those php functions that are created or defined by users.

SYNTAX:

function functionName(){
	line of codes......
}
functionName();

The function needs to be called outside of the function block to be executed.

Example

 
function printText(){
	echo 'Hello World!';
}
printText();

Functions can accept value

Value(argument/s) can be passed in a function.

SYNTAX

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);

Function can return values

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];

Variable Scope

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

Static variable preserves the last value stored in it and executes the function.

Usual Variable

function a(){
	$a = 1;
	$a++;
	return $a;
}
echo a();
echo a();
echo a();

Result 222

Static Variable

function a(){
	static $a = 1;
	$a++;
	return $a;
}
echo a();
echo a();
echo a();

Result 234

function can accept reference

function check($a){
	$a++;
}
$b=10;
check($b);
echo $b;

Result: 10

function check(&$a){
	$a++;
}
$b=10;
check($b);
echo $b;

Result: 11


0 Like 0 Dislike 0 Comment Share

Leave a comment