Search code examples
phpvar-dump

Unexpected output when using var_dump() over GLOBALS array in PHP


I have this code:

<?php

$p = 9;
$p1 = 7;

function myTest(){
    static $x = 6;
    var_dump($GLOBALS);
}

myTest();
?>

I am having the following output, can anyone help me to understand what does that output mean:

array(7) { ["_GET"]=> array(1) { ["_ijt"]=> string(26) "ahnjuf13d078eoci4stj3ke4ti" } ["_POST"]=> array(0) { } ["_COOKIE"]=> array(1) { ["Phpstorm-a9066f19"]=> string(36) "362d152a-496e-48ee-8e53-281e38eefd84" } ["_FILES"]=> array(0) { } ["GLOBALS"]=> RECURSION ["p"]=> int(9) ["p1"]=> int(7) } array(7) { ["_GET"]=> array(1) { ["_ijt"]=> string(26) "ahnjuf13d078eoci4stj3ke4ti" } ["_POST"]=> array(0) { } ["_COOKIE"]=> array(1) { ["Phpstorm-a9066f19"]=> string(36) "362d152a-496e-48ee-8e53-281e38eefd84" } ["_FILES"]=> array(0) { } ["GLOBALS"]=> RECURSION ["p"]=> int(9) ["p1"]=> int(7) }


Solution

  • $GLOBAL is a php super global variable, It returns an associative array containing references to all variables which are currently defined in the global scope of the script. where the variable names are the keys of the array. It can also be used instead of 'global' keyword to access variables from global scope

    In your case to access $p and $p1 you can follow below syntax

    <?php
    
    $p = 9;
    $p1 = 7;
    
    function myTest(){
        static $x = 6;
        var_dump($GLOBALS['p']);
        var_dump($GLOBALS['p1']);
    }
    
    myTest();
    ?>