PHP can access a global variable with global or $GLOBALS, but parameters and return values usually make dependencies clearer. Reserve global state for cases where it is genuinely part of the application's design.
<?php
function greeting(string $name): string {
return 'Hello ' . $name;
}
echo greeting('Ravi');
?>
<?php
$v1="Hello 1";
function test(){
echo "The value of \$v1= $v1";
// The above line will print The value of $v1=
global $v1;
echo "<br>The value of \$v1= $v1";
// The above line will print The value of $v1= Hello 1
$v2="Hello 2";
}
test();
echo "<br>The value of \$v2=$v2";
// The above line will print The value of $v2=
?>
In above code we have seen the local variable inside the function lost its value once function execution is completed. To retain the values for successive execution of the function we have to use static variables. Here is the code to explain about static variables.
<?php
function my_function(){
static $my_static_variable=0;
$my_local_variable=0;
$my_static_variable=$my_static_variable + 1 ;
$my_local_variable=$my_local_variable + 1 ;
echo "Static varaible :".$my_static_variable;
echo ",Local Variable :".$my_local_variable;
}
my_function();
echo "<br>";
my_function();
?>
Output is here.
Static varaible :1, Local Variable :1
Static varaible :2, Local Variable :1
The data associated with static variable is retained after the execution of the function.
$v1=2;
$v2=6;
function test(){
$GLOBALS[v3]=$GLOBALS[v1]+$GLOBALS[v2];
}
test();
echo $v3; // Output is 8
We can declare variables as Global outside the function.
$GLOBALS[v1]=2;
function test(){
$v1=5; // local variable
}
test();
echo $v1; // Output is 2 ( not 5 )
Functions Types of variables in PHP
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.
| Adam | 25-06-2014 |
| How to use the value that returned by the function, in the "if()" statement ? | |