Search code examples
phpglobal-variables

How to make global variables in php


I'm trying to create a pet site and I want to create a virtual currency system for it. But I can't find an overall php code for it to that becomes a global variable. How do I make global codes on php?


Solution

  • Your question is kinda ambiguous for me. If you mean setting a variable from one file then making it available from all your php files you can put it in one file then include the file it in all your scripts. Put it on the top. Or you can put it inside an $_SESSION variable. This is the simplest solution I know. :)

    Sample: Assuming all files are in the root directory

    vars.php:

    $globalVar = 2;
    //or 
    $_SESSION['global_var'] = 2; // if a session exists
    

    otherfile.php:

    include 'vars.php';
    echo $globalVar; //outputs 2
    //or
    echo $_SESSION['global_var']; //outputs 2
    

    I'm not sure if this is what you are trying to achieve :D