How to make a PHP variable available in all pages

I recently took a dive into wordpress, and I noticed something really unusual, When coding I noticed that a particular variable called the $post variable was available for me to manipulate whenever I need it, as along as my page is within the wp-includes, wp-themes or wp-plugins folder without me calling any external page or function.

So I started developing a site without wordpress hoping to understand the mystery behind that anomaly..

Read More

I would appreciate all help on making me understand this phenomenon. I would like to use such technique in building sites. Thanks…

Related posts

Leave a Reply

3 comments

  1. That’s not an anomaly. That variable is present in global scope and is being defined in either of the files that you have mentioned. You can easily do it like

    include.php

    <?php
    $myGlobal="Testing";
    ?>
    

    anyfile.php

    <?php
    include "include.php";
    echo $myGlobal;
    ?>
    

    And you can use it in your functions as well, as long as you refer to the global one, for example

    anotherfile.php

    <?php
    include "include.php";
    function test()
    {
     global $myGlobal;
     echo $myGlobal;
    }
    test();
    ?>
    

    Theory

    The scope of a variable is the context within which it is defined. For the most part all PHP variables only have a single scope. This single scope spans included and required files as well

    By declaring (a variable) global within the function, all references to either variable will refer to the global version. There is no limit to the number of global variables that can be manipulated by a function.

    Go through this PHP Doc once and you will have much better idea of how it all works.