php

PHP global variable with Example

Variables usually have a scope, so variables defined in one function are not available for other functions. However, it is also possible to place variables in the global scope, so that they can be accessed from anywhere. These are then accessed using the “global” keyword or the $GLOBALS array.
 

Example: Define global variable

Two global variables are defined below. These are to be accessed from a function. For this “global” or $GLOBALS must be used.

<?php
    // These two variables are automatically global because they are in the top(outside of all functions)
    $var1 = 'It is a global variable';
    $var2 = 'This is also a global variable';
 
    function test() 
    {
        // for the rest of this function $var1 can be accessed directly
        global $var1;
        echo($var1 . "\n");
        
        // only one-time access to global variable $var2
        echo($GLOBALS['var2'] . "\n"); 
        
        // Now $var2 is no longer known, an error occurs
        echo($var2 . "\n"); 
    }
     
    test();
?>

Output:

It is a global variable
This is also a global variable

Notice:  Undefined variable: var2 in [...][...] on line 17
PHP Variable ScopePHP Variable ScopeWhich areas of application or scopes exist and what effects this has on access to variables? According to the name, the scope of a variable…Read More
Example: Marking several variables as global

The keyword “global” can also be applied to several variables at the same time.

<?php
    $var1 = 'globale Variable 1';
    $var2 = 'globale Variable 2';
    $var3 = 'globale Variable 3';
 
    function test() 
    {
        global $var1, $var2, $var3;
        
        echo $var1, ", ", $var2, ", ", $var3;
    }
     
    test();
?>

Output:

globale Variable 1, globale Variable 2, globale Variable 3

 

Example: class instead of global variables

Instead of global variables, classes should be used, which improves the readability and maintainability of the code.

<?php
    class Config {
        public static function getGlobalVar1() {
            return 'globalVar1';
        }
 
        public static function getGlobalVar2() {
            return 'globalVar2';
        }       
    }
 
    function test() {
        echo(Config::getGlobalVar1() . "\n");
        echo(Config::getGlobalVar2() . "\n");
    }
 
    test();
?>

Output:

globalVar1
globalVar2
PHP MCQ - Multiple Choice Questions and AnswersPHP MCQ – Multiple Choice Questions and Answers – Basics – Part 1This collection of PHP Multiple Choice Questions and Answers (MCQs): Quizzes & Practice Tests with Answer focuses on “PHP basic”.   1. In PHP, variables…Read More mcqMCQPractice competitive and technical Multiple Choice Questions and Answers (MCQs) with simple and logical explanations to prepare for tests and interviews.Read More

Leave a Reply

Your email address will not be published. Required fields are marked *