phpphp-5.4

Global variable not working in php


I am facing some errors with use of global variables. I defined a $var in global scope and trying to use it in functions but it not accessible there. Please see below code for better explanation:

File a.php:

<?php

  $tmp = "testing";

  function testFunction(){
     global $tmp;
     echo($tmp);
  }

So a bit about how this function is called.

File b.php:

<?php
  include 'a.php'
  class testClass{
    public function testFunctionCall(){
        testFunction();
    }
  }

The above 'b.php' is called using:

$method = new ReflectionMethod($this, $method);
$method->invoke();

Now the desired output is 'testing' but the output received is NULL.

Thanks in advance for any help.


Solution

  • You missed calling your function and also remove the protected keyword.

    Try this way

    <?php
    
      $tmp = "testing";
    
      testFunction(); // you missed this
    
      function testFunction(){  //removed protected
         global $tmp;
         echo($tmp);
      }
    

    Same code but using $GLOBALS, gets you the same output.

    <?php
    
    $tmp = "testing";
    
    testFunction(); // you missed this
    
    function testFunction(){  //removed protected
        echo $GLOBALS['tmp'];
    }