0

So I know I can use __callStatic() to allow for:

Example::test(); 

Too work... But what I was wondering if its possible to overload

Example::test->one()
Example::test->two()

Is this possible at all with PHP? If so does anyone have a working example?

Or does anyone know of a work around?

Edit

Thought I would add some more details on why am wanting to do this and its basically cause I have a API with has methods like api.method.function and want to build a simple script to interact with that api.

There is also some methods that are just api.method

1 Answer 1

4

To quote the manual:

__callStatic() is triggered when invoking inaccessible methods in a static context.

So it doesn't work with properties - what you would need for your example to work as you described it is __getStatic. But, that doesn't exist.

The closest workaround that I can think of would be to use something like:

Example::test()->one();
Example::test()->two();

Where test() can be defined through __callStatic and it returns an object which has the methods one and two, or has __call defined.

EDIT:

Here's a small example (code hasn't been tested):

class ExampleTest {
    public function __call($name, $arguments) {
        if ($name == 'one') {
            return 'one';
        }

        if ($name == 'two') {
            return 'two';
        }
    }
}

class Example {
    public static function __callStatic($name, $arguments) {
        if ($name == 'test') {
             // alternatively it could be return ExampleTest.getInstance() if you always want the same instance
            return new ExampleTest();
        }
    }
}
Sign up to request clarification or add additional context in comments.

5 Comments

I spotted the __call function and that does mention Objects, but I wasn't sure if I could call it from within __callStatic and do what I needed. Not really thought of how I can test that yet...
But you wouldn't define it within __callStatic, you would define it on the class of the object that's returned by test(). If it's still unclear let me know and I'll add an example.
would this require predefined functions though? As I was hoping to do it all dynamically incase they ever changed, updated or removed method and functions out of the API.
I don't really understand what you mean by "predefined". The example class uses __call, so you can call any methods on it, I've just written an example implementation for one and two, but you can do whatever you want inside it, based on the function name. EDIT: I think I understand, you are refering to the test method, right?
I will give this a try and see what happens for what I need.

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.