0

I've defined a variable in my child theme header.php.

I'd like to get the value of this variable from one of the templates that is rendered after the request in which the header.php is called.

So, in header I've got this:

$foo = "bar"

If I test for this value with header.php, it returns "bar". But if I test for the value from a template called after the header gets called, I get 'null'.

The first thing I tried was putting 'global $foo' before the definition of $foo. But this didn't change my result.

-2

It the template is called via get_template_part(), then it is in a new variable scope. to access it, you have to use the global keyword in you template file:

global $foo;
echo $foo;

As header.php probalbly is also called in a function scope, you have to make sure there the variable is used in global scope when definig it:

global $foo;
$foo = 'bar';
  • 1
    seriously, using global in 2016? even in php land there is no excuse to do that anymore – Mark Kaplun Nov 23 '16 at 5:32
1

Don't muddy up the $_GLOBAL space. If you want to nix the class route and use a function with a statically scoped variable you can keep it contained.

// getter + setter function 

function prefix_my_var( $value = null ) {
    static $s = null;
    if ( ! is_null( $value ) ) {
        $s = $value;
    }

    return $s;
}

// set + get

$value = prefix_my_var( 'foo' ); // foo

//  get

$value = prefix_my_var();        // foo

Now if you pass a value it'll set+get it. And if you don't pass a value it'll just get the current value.

echo "<pre>";
print_r( array (
        prefix_my_var(),
        prefix_my_var( 'foo' ),
        prefix_my_var(),
        prefix_my_var( 'bar' ),
        prefix_my_var(),
        prefix_my_var( 'baz' ),
    ) );

Array
(
    [0] => 
    [1] => foo
    [2] => foo
    [3] => bar
    [4] => bar
    [5] => baz
)
0

If you're going to pass on numerous values across different template files, I suggest using a static class to store an array.

// In your functions.php
class Var
{
    public static $foo;
    public static function set_var($value;)
    {
        self::$foo = $value;
    }

}

// In your header.php
\Var::set_var(array(
    'var1' => 'value1',
    'var2' => 'value2',
));

Now you can just call the class statically anywhere else to access the data.

// Displays 'value1'
echo \Var::$foo['var1'];

// Displays 'value2'
echo \Var::$foo['var2'];

Might seem like overkill for passing a few variables, but at least you have the option of expanding the array if you need to pass much more information.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.