functions - How to access custom class methods from any include without using global

I am trying to do the followingfunctions.phpclass Test {public function hello(){return 'Hello';}}$test = new

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?

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745539289a4632051.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信