Chrome Extension

Access global variable inside a function PHP

    $globalVal = "I am a global variable";

    function printVal() {
        global $globalVal;

        echo $globalVal;

We are a bunch of lazy programmers so we developed this chrome extension
search code from your favorite search engine
Install Now
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?
Open Code Manager We are hiring