Search code examples
phpsuperglobals

use of $GLOBALS in php


I am new to php so I do not know much about $_GLOBALS. I expect these are used to access global variables anywhere. So, my question is what is the problem inside function addition(), why I cannot do this? Can't I directly assign a value to the variable z.

    <?php 
    $x = 75; 
    $y = 25;

    function addition () { 
        $z = $GLOBALS['x'] + $GLOBALS['y']; 
    }

    addition(); 
    echo $z; 
    ?>

I get following error:

Notice: Undefined variable: z in C:\xampp\htdocs\php\first.php on line 14

which is echo $z;


Solution

  • If you start with programming I can highly recommend you not to use GLOBALS. There are better ways to get object/variable than globals. For example dependency injection

    Function is something what takes arguments does something with them and return value. So you can create addition function

    function addition ($x, $y) {
      return $x + $y;
    }
    

    when invoked this will return sum of $x and $y. When you have this value you can for example output it to user with echo

    echo addition(5, 4);
    

    or

     $z = addition(5, 4);
     echo $z;
    

    In your case you get notice because you want to get variables that are not set. You can check if variable is set with function isset($variable)

    If you still want to use $_GLOBALS then you need to know what $_GLOBALS is. It's reference for all variables in global scope so to make it work you should write something like

    $x = 5;
    $y = 7;
    
    function addition() { 
        return  $GLOBALS['x'] + $GLOBALS['y']; 
    }
    
    echo addition();
    

    But this is bad approach and I better don't do it.

    Edit:

    Check also this link