Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Global variable not working in php

Tags:

php

php-5.4

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.

like image 971
spuri Avatar asked Sep 17 '13 11:09

spuri


People also ask

How do global variables work in PHP?

Global variables refer to any variable that is defined outside of the function. Global variables can be accessed from any part of the script i.e. inside and outside of the function. So, a global variable can be declared just like other variable but it must be declared outside of function definition.

Does PHP have global variables?

Some predefined variables in PHP are "superglobals", which means that they are always accessible, regardless of scope - and you can access them from any function, class or file without having to do anything special. The PHP superglobal variables are: $GLOBALS.

What are the problems with global variables?

Global variables can be altered by any part of the code, making it difficult to remember or reason about every possible use. A global variable can have no access control. It can not be limited to some parts of the program. Using global variables causes very tight coupling of code.

What is difference between static and global variable in PHP?

Global is used to get the global vars which may be defined in other scripts, or not in the same scope. e.g. Static is used to define an var which has whole script life, and init only once.


1 Answers

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'];
}
like image 106
Shankar Narayana Damodaran Avatar answered Sep 22 '22 16:09

Shankar Narayana Damodaran