Using Global Variables Expensive for PHP

Here is a basic class which you can create once:

if ( ! class_exists('my_class') ) :

class my_class {

    public $my_var;

    // This variable is for a single instance
    static $instance;

    function __construct () {
        // Call other methods like this
        $this->initialize();
    }

    function initialize () {
        // Populate your variables here
        $this->my_var="any value you want";
    }

    static function get_instance () {
        // Static variables are persistant
        // Notice the 'self::' prefix to access them
        if ( empty(self::$instance) )
            self::$instance = new my_class();
        return self::$instance;
    }    
}

endif;

Now in your template files you can access the class like this:

<?php $var = my_class::get_instance()->my_var; ?>

Leave a Comment

tech