php
Access global variable inside a function PHP
<?php
$globalVal = "I am a global variable";
function printVal() {
global $globalVal;
echo $globalVal;
}
printVal();
?>
Output
I am a global variable
If you want to access a global variable inside a function in PHP, you can use this by adding a 'global' keyword before the variable name inside the function. You can directly access a variable inside a function without adding it.
In our code snippet, we have declared a global variable named $globalVal. If you will directly use it inside the function printVal(), it will show an error of undefined index globalVal. We will have to use global $globalVal to access this.
Was this helpful?
Similar Posts