setting variable in header.php but not seen in footer.php

后端 未结 5 1192
醉梦人生
醉梦人生 2021-02-19 02:24

in wordpress , i set a variable in header.php


but in footer.php when I ech

5条回答
  •  一向
    一向 (楼主)
    2021-02-19 03:01

    I know you've already accepted the answer to this question; however, I think there's a much better approach to the variable scope problem than passing vars into the $GLOBALS array.

    Take the functions.php file in your theme for example. This file is included outside the scope of the get_header() and get_footer() functions. In fact it supersedes anything else you might be doing in your theme (and I believe in the plugin scope as well--though I'd have to check that.)

    If you want to set a variable that you'd like to use in your header/footer files, you should do it in your functions.php file rather than polluting $GLOBALS array. If you have more variables that you want to sure, consider using a basic Registry object with getters/setters. This way your variables will be better encapsulated in a scope you can control.

    Registry

    Here's a sample Registry class to get you started if:

    properties[ $index ] = $value;
        }
    
        /**
         * @get     mixed   Objects stored in the registry
         * @param   string  $index  A unique ID for the object
         * @return  object  Returns a object used by the core application.
         */
        public function __get($index)
        {
            return $this->properties[ $index ];
        }
    
        # +------------------------------------------------------------------------+
        # CONSTRUCTOR
        # +------------------------------------------------------------------------+
        public function __construct()
        {
        }
    
    
    }
    

    Save this class in your theme somewhere, e.g. /classes/registry.class.php Include the file at the top of your functions.php file: include( get_template_directory() . '/classes/registry.class.php');

    Example Usage

    Storing variables:

    $registry = new Registry();
    $registry->my_variable_name = "hello world";
    

    Retrieving variables:

    echo '

    ' . $registry->my_variable_name . '

    '

    The registry will accept any variable type.

    Note: I normally use SplObjectStorage as the internal datastore, but I've swapped it out for a regular ole array for this case.

提交回复
热议问题