PHP Variable Usage inside of Function

Besides more than thousands of built-in functions PHP provides facility to define custom/user defined function. How to define and call a user defined function was discussed in previous article. Variable plays an important role in any PHP user defined function. Variables used in PHP function can be categorized as local, global and static variables.

A PHP programmer should understand how to use local, global and static variables in a PHP function. So, in this article, I am going to discuss how to define and use local, global and static variables inside a PHP function.

Variables in PHP Function

Variables in PHP Function

According to variable scope and usage in PHP function, variables can be categorized into the following three types.

  • PHP local variable in function
  • PHP static variable in function
  • PHP global variable in function

PHP Local Variable in Function

Local variables are those variables which are defined and used within a PHP function. So, if we define a variable within a PHP function, the variable will be local variable. After executing the function, defined local variables will be erased from the memory. So, we cannot reuse local variable outside of a function. If we use a local variable outside of a function, PHP compiler will show an error message.  

The following program is a simple example of local variable declaration and its usage inside a PHP function.

<?php
function show(){
 $a=15;
$b=20; 
echo "Local variable a = ".$a." and b = ".$b;
}
show();
?>

Output

Local variable a=15 and b=20

Here, two variables are declared and assigned values within the show() function. So, these variables are local variable of the show() function.  The show() function is showing the local variable values when it is called from the program.

Declaring Local Variable as Function Parameter

In this example, we have assigned local variable’s value within function. But local variable’s value is usually not assigned within function because we can never change local variable’s value at the time of function calling if we assign variable value within function.  If we require changing local variable value at function calling, we need to declare local variables as function parameters.

The following program is a simple example of declaring local variable as function parameter.

<?php
function add($a,$b)
  return ($a+$b);
}
echo “The sum of 10 and 12 is: ”.add(10,12); 
?>

Output

The sum of 10 and 12 is: 22

Here, two local variables $a and $b have been declared as function parameter and assigning variable value at the time of function calling. In this example, the value of function parameter must assign at function calling otherwise PHP compiler will show an error message. To make error free coding, we can assign local variables default value at the time of function and local variable declaration.

Assigning Function Default Argument Value

In PHP programming it is possible to assign local variables default value at the time of function and local variable declaration which is known as assigning function default argument value. If we assign local variable’s default value, no chance to gets error message if we forget to assign value at function calling.

The following program is a simple example of assigning local variable’s default value at the time of function declaration.

<?php
function add($a=0,$b=0){
  return ($a+$b);
}
//calling function with arguments
echo "The sum of 10 and 12 is: ".add(10,12)."<br>";
//calling function without arguments 
echo "The sum is : ".add(); 
?>

Output

The sum of 10 and 12 is: 22

The sum is: 0

In this example we have defined function’s default argument value at function declaration. So, if we forget to pass value at function calling, we get a result rather error message.

Declaring Variable Type in Function Parameter

As I told in PHP data types and variables discussion, PHP is a loosely typed programming language. So, we should careful enough while calling function with arguments. If data type of a variable used in function’s algorithm does not match while calling function with arguments, desired result cannot be found and program error will occur.

For example, in the above program, notice that we have not told PHP which data type the variable is.

PHP automatically associates a data type to the variable, depending on its value. Since the data types are not set in a strict sense, you can do things like adding a string to an integer without causing an error.

In PHP 7, type declarations were added. This gives us an option to specify the expected data type when declaring a function, and by adding the strict declaration, it will throw a “Fatal Error” if the data type mismatches.

For example, in the following program, we are tryinng to send both a number and a string to the function without using strict.

<?php
function add(int $a, int $b) {
  return $a + $b;
}
echo add(5, "5 days");
?>

Since strict is NOT enabled “5 days” is changed to int(5), and it will return 10.

To specify strict, we need to set declare(strict_types=1);. This must be on the very first line of the PHP file.

In the following example, we are trying to send both a number and a string to the function, but here we have added the strict declaration. So, we will expect an error messge from PHP compiler.

<?php 
declare(strict_types=1); // strict requirement

function add(int $a, int $b) {
  return $a + $b;
}
echo add(5, "5 days");
?>

Since strict is enabled and “5 days” is not an integer, an error will be thrown by the PHP compiler.

PHP Static Variable in Function

Local variable is normally erased after executing any function. But local variable can be stored using static keyword. The static keyword makes any variable static storing the variable in memory. The value of a static variable is assigned only once in a function.

The following program is an example of PHP static variable in function where a variable is being stored in memory although execution of the function has been completed.

<?php
function show(){
static $count=0;
$count++;
print("show() called ".$count." times <br>");
}
show();
show();
show();
?>

Output

Show() called 1 times

Show() called 2 times

Show() called 3 times

Here, the $count variable is a static variable. Being static variable the $count variable is not being erased after calling the show() function. Also notice that the value 0 is being assigned only once and each calling the previous value is being retrieved.

PHP Global Variable in Function

Global variables are those variables which are accessible from anywhere of a page. In the view of a PHP function, the global variables are those variables which are declared outside and at top of a function. Global variables cannot be used directly in PHP function. If we need to use a global variable within a function, the variable must declare with global keyword inside that function.

The following program is a simple example of PHP global variable used within a function.

<?php
$a=5;
function add(){
  global $a;
  $b=10;
  $c=$a+$b;
  echo "The sum is:".$c;
}
add();
?>

Output

The sum is: 15

Here, the variable $a has been declared outside of add() function. So, $a is a global variable. To use this global variable within add() function, the $a variable has been declared with global keyword. If we don’t declare global variable with global keyword, the value of global variable cannot be used within PHP function.

If we use global variable within a function and change the variable’s value, the value of global variable will be changed and the changed value will be got if we use global variable outside of the function.

The following program is an example of global variable usage where value of global variable is being changed within function and the changed value is being found outside of the function.

<?php
$a=5;
$b=10;
function show(){
global $a;
$a=15;
$b=20;
echo "Global variable a = ".$a." and local variable b = ".$b;
}
show();
echo "<br>Global variable a is now ".$a." and b = ".$b;
?>

Output

Global variable a=15 and local variable b=20

Global variable a is now 15 and b=10

The global variable $a has been declared within function with the global keyword. So, the global variable is now being used in the function and the value is being changed. Again, the variable $b is also declared in the function but without global keyword. So, the value of global variable $b is not being changed because the variable $b is using as local variable in the function.

Difference between Global and Static Variable in PHP

Although the value of global and static variable can be changed within PHP function and kept until program execution finished, the static variable only accessible within function but global variable can accessible anywhere of a PHP program.    

How to use variables in PHP function has been discussed in this article. I hope you will now be able to use variables in PHP function properly. However, if you face any confusion to use variable in PHP function, feel free to discuss in comment or contact me from Contact page. I will try my best to stay with you.

I am a system administrator and like to share knowledge that I am learning from my daily experience. I usually work on MikroTik, Redhat/CentOS Linux, Windows Server, physical server and storage, virtual technology and other system related topics. Web development is also my favorite topic and love to work with PHP, HTML, CSS, Tailwindcss, Bootstrap, JavaScript, jQuery, Vue.js, WordPress and Laravel framework. Follow Me: Facebook, Twitter and Linkedin.

Related Posts

Laravel First Time Installation on Windows 10/11

Laravel is one of the best full stack frameworks used to develop modern web application simply and securely. Day by day PHP developers are absorbing Laravel. So,…

PHP Delete Array Element with Built-in Function

Array is an important and mostly used data type in PHP programming. PHP programmer can manually add element to an array or delete element from an array…

PHP Add Element to Array with Built-in Functions

Array plays an important role in PHP programming. It is one of the most used data structures in PHP programming. So, it is better to have a…

PHP Array Explanation

Array is one of the most important and basic terms in PHP Language. Almost all the PHP program uses array data structure. So, those who want to…

Function Call by Value and Call by Reference in PHP

More than thousands of built-in functions proves the power of PHP Language. Besides built-in function PHP allows to create user defined function. How to create user defined…

PHP Function Explanation

Real power of a programming language comes from its functions. More than thousands of built-in functions defined in PHP language proves the power of PHP language. Besides…

Leave a Reply

Your email address will not be published.

*

This site uses Akismet to reduce spam. Learn how your comment data is processed.