• Resolved Kevin

    (@truheart)


    I am trying to get a feel for what are the best practices when needed to have reusable variables across theme files. Right now I a settings.php file that is being included within functions.php. In this file I would like to assign variables for global settings such as directory paths, module names, etc.

    Here is a very basic rundown of what I would do if I were to use globals:

    /**
     * Directories
     */
    $GLOBALS['theme-dir']	     = get_stylesheet_directory_uri();
    $GLOBALS['styles-dir']	     = $GLOBALS['theme-dir'] . '/dist/styles';
    $GLOBALS['scripts-dir']	     = $GLOBALS['theme-dir'] . '/dist/scripts';
    $GLOBALS['fonts-dir']	     = $GLOBALS['theme-dir'] . '/dist/fonts';
    $GLOBALS['fc-layouts-dir']   = 'templates/fc-layouts';
    
    /**
     * Layouts
     */
    $layouts = [
    	'blue-highlights',
    	'carousel',
    	'centered-content',
    	'custom',
    	'hero',
    	'list-items',
    	'product-highlights'
    ];
    
    $GLOBALS['fc-layouts'] = array();
    
    if( $layouts ) {
    	foreach( $layouts as $layout ) {
    		$GLOBALS['fc-layouts'][] = $layout;
    	}
    }

    Now to be safe I would probably need to “namespace” the global variable names, but I’m assuming that this is not the best way to do this and I know usually people want to stay away from using globals like this. Is there a cleaner way to achieve similar results using classes?

Viewing 2 replies - 1 through 2 (of 2 total)
  • Moderator bcworkz

    (@bcworkz)

    Of course! You’ll probably want to declare such properties static and then define methods to access the property. Otherwise you would need to instantiate the class object and then you’ll have the same issue of needing a global object in order to access non-static properties.

    To a large extent we are just using global values in a different way by using static properties, but it does prevent name collisions and well named classes and properties make your code much more readable. And then you can exclaim “Look Ma! No globals!” 🙂

    Thread Starter Kevin

    (@truheart)

    Yup… as usual, thanks BC.

Viewing 2 replies - 1 through 2 (of 2 total)
  • The topic ‘Globals vs. classes to store theme config’ is closed to new replies.