The function called on the wp head hook becomes null

As an alternative you could try declaring it with $GLOBALS['a3'] in file2 to make sure it becomes a global:

$GLOBALS['a3'] = Sample_Class::instance();

I’d guess the current $a3 declaration in file2’s top level scope doesn’t count as global because it gets inluded inside the test_loaded() scope. From the ‘include’ docs (which cover require and require_once too):

When a file is included, the code it contains inherits the variable scope of the line on which the include occurs. Any variables available at that line in the calling file will be available within the called file, from that point forward. However, all functions and classes defined in the included file have the global scope.

So it looks like variables declared at file scope in an included file are an exception to true global scope. However I’m surprised there’s not an equivalent exception to allow them to be accessed as globals from file2 anyway, since that changes how $a3 behaves depending on how the file can be included.


If you don’t need $a3 to be global outside file2, another option might be to change sample2() into an anonymous closure that includes $a3 with a ‘use’:

$a3 = Sample_Class::instance();

add_action( 'wp_head', function() use ($a3) {
    echo $a3->sample('test');
});