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?

  • There are a few ways, but they have advantages and disadvantages depending on what your class method does, can you provide some context to narrow things down a little as to what your class does? Otherwise any answer would be super long in order to cover all bases, which puts people off answering – Tom J Nowell Apr 29 at 12:19
  • @TomJNowell Thank you, I want to add utilities class with different methods but I can't access any from includes, templates without instantiation of the class. This is why I am trying to find a way of doing it from functions. I see that I can instantiate it from header.php and just add all variables over there but it just looks dirty, isn't it. There is no hook to do that instead? – Alex Apr 29 at 12:56
  • I wouldn't use header.php for anything other than displaying the header. Just keep in mind that what you're doing isn't OOP, so unless your class has internal state, your might be better off just using functions with an appropriat prefix to avoid clashes – Tom J Nowell Apr 30 at 0:15
  • Thank you @TomJNowell I made an update to my question with possible solution. I know this is not exactly what you meant but I really would like to keep my methods inside the class but the idea with functions brought me an idea that I could just return an instantiation and that would work. Would you say that it is ok? – Alex Apr 30 at 9:08

Your Answer

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

Browse other questions tagged or ask your own question.