Chrome Extension

Access global variable inside a function PHP

<?php
    $globalVal = "I am a global variable";

    function printVal() {
        global $globalVal;

        echo $globalVal;
    }

    printVal();
?>
Best JSON Validator, JSON Tree Viewer, JSON Beautifier at same place. Check how cool is the tool
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?
0 Comments