• Resolved goldenhills

    (@goldenhills)


    I want to add a gloabal variable once and then reference it on many pages. The value will change once a year so I would like to only have to update one file for it to automatically update all the pages.

    I am new at this. Can someone tell me if this will work or if there is an easier or better way?

    In my page.php file add:
    <?php global $CurrentYear = 'dog'; ?>

    Then on any page I can add:
    <?php echo 'This is the year of the ' . $CurrentYear; ?>

    Thank you!

Viewing 4 replies - 1 through 4 (of 4 total)
  • you need to include the file with the variable into the file you want to call that variable from…. i.e

    page.php

    <?php
    $CurrentYear = 'dog';
    ?>

    any page

    <?php
    include 'page.php';
    echo $CurrentYear;
    ?>

    if you are trying to call the variable from within a function, you need to call it globally

    <?php
    include 'page.php';
    function year(){
        global $CurrentYear;
        echo $CurrentYear;
    }
    echo year();
    ?>
    Thread Starter goldenhills

    (@goldenhills)

    Oh. Somehow that seems inefficient. Is there no other way to do this that would be better? Maybe a define or something?

    Thanks for your reply!

    you can define it, but it would still need to be included,

    you could always put the variable into the config file, as the config file is called with almost every page

    add it into the config, then you should be able to call it
    if set as a variable, then you will need to use global if inside a function,
    or you can define it, thus no global needed,

    define('CURRENT_YEAR', 'dog');

    echo CURRENT_YEAR;

    Thread Starter goldenhills

    (@goldenhills)

    That sounds like just what I am looking for. Thank you very much!

Viewing 4 replies - 1 through 4 (of 4 total)
  • The topic ‘Using a global variable’ is closed to new replies.