admin管理员组

文章数量:1429658

I am trying to do the following

functions.php

class Test {

    public function hello(){
        return 'Hello';
    }

}
$test = new Test();

header.php or any other include

echo $test->hello();

But it is not accessible unless I define it as:

global $test;
echo $test->hello();

I really do not want this as I will end up with many variables to define. Is there anyway to make class object and methods being accessible from any include?

Thank you so much.


UPDATE, POSSIBLE SOLUTION

At the end I did the following:

functions.php

Included the class with require.

Added a function that returns instantiation of specific class

function test(){
    return new Test();  
}

And then it's methods become accessible from anywhere: includes, templates just like this:

header.php or any custom include or template

echo test()->hello();

That does work and I do not need to use $GLOBALS, I just hope I am not doing something awkward in terms of WordPress.

Would you approve that?

本文标签: functionsHow to access custom class methods from any include without using global