PHP global variables in function and class 

Joined:
03/10/2011
Posts:
84

April 28, 2011 21:09:08    Last update: April 28, 2011 21:09:08
PHP global variables are defined outside of functions and classes. They are visible both in the current file and in any included/required files. Also, any global variables defined in required/included files are visible in the current file. But they are not visible in any functions or classes, unless specifically declared global.

Test:
  1. Create file test.php:
    <?php
    ini_set('display_errors', 'stderr');
    ini_set('error_reporting', E_NOTICE);
    
    // $a and $b available in test.inc
    $a = 'a';
    $b = 'b';
    
    include "test.inc";
    
    echo '[', __FILE__, '] $c + $d = ', $c + $d, "\n";
    
    function concat() {
        echo '[', __FUNCTION__, '] $a . $b = ', $a . $b, "\n";
    }
    
    function concat_global() {
        global $c, $d;
        echo '[', __FUNCTION__, '] $c + $d = ', $c + $d, "\n";
    }
    
    class A {
        function __construct() {
    	echo '[', __CLASS__, '] $c + $d = ', $c + $d, "\n";
        }
    }
    
    class B {
        var $e = 'e';
        private $f = 'f';
        function __construct() {
    	global $a, $b;
    	echo '[', __CLASS__, '] $a . $b = ', $a . $b, "\n";
    	echo '[', __CLASS__, '] $e . $f = ', $e . $f, "\n";
    	echo '[', __CLASS__, '] $this->e . $this->f = ', $this->e . $this->f, "\n";
        }
    }
    
    concat();
    concat_global();
    new A();
    new B();
    ?>
    

  2. Create file test.inc:
    <?php
        echo '[', __FILE__, '] $a . $b = ', $a . $b, "\n";
    
        // $c and $d available in test.php
        $c = '1';
        $d = '2';
    ?>
    

  3. Run the PHP script in command line:
    php test.php 2>C:\tmp\stderr.out
    

  4. The result is:
    [C:\work\test.inc] $a . $b = ab
    [C:\work\test.php] $c + $d = 3
    [concat] $a . $b =
    [concat_global] $c + $d = 3
    [A] $c + $d = 0
    [B] $a . $b = ab
    [B] $e . $f =
    [B] $this->e . $this->f = ef
    

  5. stderr messages:
    PHP Notice:  Undefined variable: b in C:\work\scrap\test.php on line 14
    Notice: Undefined variable: b in C:\work\scrap\test.php on line 14
    PHP Notice:  Undefined variable: a in C:\work\scrap\test.php on line 14
    Notice: Undefined variable: a in C:\work\scrap\test.php on line 14
    PHP Notice:  Undefined variable: d in C:\work\scrap\test.php on line 24
    Notice: Undefined variable: d in C:\work\scrap\test.php on line 24
    PHP Notice:  Undefined variable: c in C:\work\scrap\test.php on line 24
    Notice: Undefined variable: c in C:\work\scrap\test.php on line 24
    PHP Notice:  Undefined variable: f in C:\work\scrap\test.php on line 34
    Notice: Undefined variable: f in C:\work\scrap\test.php on line 34
    PHP Notice:  Undefined variable: e in C:\work\scrap\test.php on line 34
    Notice: Undefined variable: e in C:\work\scrap\test.php on line 34
    

Share |
| Comment  | Tags