0

I want to use a class method in multiple files. Instead of declaring an object in each file, is it possible to create the object in a function and use this function where I need it?

Example:

class Test_Class {

    public function test_method() {
        // something
    }

}

function Test_Class_Init(){
    $test_class = new Test_Class();
    return $test_class;
}

Then call the method in this way in each file:

Test_Class_Init()->test_method();
6
  • 1
    Is Test_Class_Init() really saving you anything over just running new Test_Class? Or are you asking about how to share a single instance of the object (i.e. a singleton)? Commented Nov 23, 2018 at 16:47
  • well yes, but it's really just a level of indirection. You still have to write a line of code everywhere you need it. It's just a different line of code. Not really clear how this helps you, unless in reality initialising the class requires some more complex setup with multiple lines of code to set properties etc Commented Nov 23, 2018 at 16:48
  • If, as iainn mentions, you really want one instance (i.e. one copy) of the class to be shared everywhere, then google the Singleton Pattern Commented Nov 23, 2018 at 16:48
  • You may also use a static method. Commented Nov 23, 2018 at 16:49
  • No I don't need a single instance, this is just an idea for not declare over and over again the same object in a lot of file Commented Nov 23, 2018 at 17:18

1 Answer 1

1

If your method is not reliant on any other data in the class, you could consider declaring it as static...

class Test_Class {
    public static function test_method() {
        echo "Hello";
    }
}

you can then call it just referencing the class...

Test_Class::test_method();
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.