0

Why I am not able to get the $somevar on getVar()

I am getting this error while using print "Somevar is ". GLOBAL $somevar;

Line : 10 -- syntax error, unexpected 'GLOBAL' (T_GLOBAL)

and

E_NOTICE : type 8 -- Undefined variable: somevar -- at line 10

when using witout GLOBAL print "Somevar is ". $somevar;

<?php
   $somevar;

   function setVar() {
      GLOBAL $somevar;
      $somevar++;
   }

   function getVar() {
      print "Somevar is ".  GLOBAL $somevar;
   }
   setVar();
   getVar();
?>
Atanas
  • 366
  • 2
  • 17
Behseini
  • 6,066
  • 23
  • 78
  • 125

1 Answers1

0

From what you have shown to us I see some issues on your code:

  1. You have not assigned any value to $somevar
  2. You have missed a $ sign at the beginning of the GLOBALS keyword (and you missed an S letter at the end)
  3. $GLOBALS is a superglobal variable and it is actually an array - so to access the $somewar value you have to type something like this $GLOBALS['somevar']

I will provide you with an example of how to work with global variables

$name = 'John';

function getGlobalVarName() {
 return $GLOBALS['name'];
}

echo getGlobalVarName();

Read more about variable scope (global variables) here: Variable Scope in PHP

Ylber Veliu
  • 349
  • 2
  • 13