Search code examples
phpvariablessuperglobals

Store my own super global variable within PHP files?


I am building a website that will have hundreds of pages. Each of these pages will have a title, like:

The Best Webpage in the world - Stackoverflow

As above every page will have the sites name following the page title.

I want store the sites name in some sort of global variable.

This is so I will not need to manually change hundred's of page titles in-case the sites name changes.

Now I could just store the name in a file and use require_one to include it.

But I was hoping for a more elegant solution. That allows me to store title within php files, and call it in the same way you call a PHP GET etc.


Solution

  • The simplest you can do (and what I would recommend) is something like this:

    // This is included in every page (maybe as part of including config.php or equivalent)
    define('SITE_NAME', 'Stackoverflow');
    
    function get_title($title) {
        return sprintf('%s - %s', $title, SITE_NAME);
    }
    
    // This is in one of your pages
    echo get_title('The best webpage in the world');
    

    See it in action.