How to Use Static Variables in PHP?

We will use the static variable just to retain the state of variable in our PHP code. But why we need that? Let’s check this simple recursive code.

$numbers = [ 12, 10, 2, 11, 4, 8, 9, 6, 7, 1, 3, 5 ];
$total   = 0;
function sum_function( $size, $numbers, $total ) {
	$total += $numbers[ $size ];
	if ( $size < 0 ) {
		return $total;
	}
	$size --;

	return sum_function( $size, $numbers, $total );
}

In this code, we are declaring a variable out of the function and then passing it to the function to calculate total sum of elements in our array. Now here clearly we are passing one extra variable. Because all the variables we will declare inside, the function will be lost when while exiting. How? Lets try this code.

function sum_function( $size, $numbers ) {
	$total = 0;
	if ( $size < 0 ) {
		return $total;
	}
	$size --;
	$total += $numbers[ $size ];

	return sum_function( $size, $numbers );
}

Now in this code we saved one variable by making $total local to our sum_function. But that will create another problem. It will declare and initialise $total=0 every time we will call that function. So our total sum will remain 0. Which is a horrible result. Now lets see the magic of ‘static’ keyword?

$numbers = [ 12, 10, 2, 11, 4, 8, 9, 6, 7, 1, 3, 5 ];

function sum_function( $size, $numbers ) {
	static $total = 0;
	if ( $size < 0 ) {
		return $total;
	}
	$size --;
	$total += $numbers[ $size ];

	return sum_function( $size, $numbers );
}

That code will work fine and we just saved ourselves with one variable. Now key concept is static variable will be declared only one time and after that whenever that line will be called, it will retain its state or that line will be skip passed simply. Easy to remember. At end of the function static variable will return its retained value.