最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin1浏览0评论

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?

发布评论

评论列表(0)

  1. 暂无评论