2

is there a way to write a class that can be called like a function? I mean something like this:

class test{}
$test = new test;
$test();

I tried with the __call magic method but it can be used only when accessing in-existent methods on it. Maybe it can be done using SPL classes or interfaces?

5
  • 1
    What are you trying to produce? Commented Sep 7, 2011 at 7:42
  • 1
    $someclass() isn't descriptive. It does in no single way describe what you intend to do, to readers of your code. Function names should be descriptive, they should show you (and again, the readers of your code who don't know your intent, which might very well be you in a couple of months). So: think of what you want to do, and create a function for it. $test->GetFoo() or $test->CreateBar() show what you do in the function, without having to look at it. Commented Sep 7, 2011 at 7:45
  • @CodeCaster you're right but it can be useful to add a shortcut to the most important method of the function for example Commented Sep 7, 2011 at 7:48
  • I'm sorry, but to me that still doesn't qualify as a valid excuse. It isn't clear what's going to happen to $test, in what state it needs to be, if it returns something and what, whether you can expect it to go wrong, and so on. Commented Sep 7, 2011 at 7:51
  • 1
    I don't agree with you. If you have a valid documentation you can do everything. If document the code and i write a tutorial saying that the test class can be called as a function to do a specific task i don't see any problem. Commented Sep 7, 2011 at 7:57

1 Answer 1

5

Use the __invoke magic method:

class test{
    public function __invoke()
    {
        return 'fooo';
    }
}

$test = new test;
print $test();

But you need PHP 5.3 for this.

Another alternative depending on what you are trying to do might be using a closure.

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.