Guillaume Bois
Guillaume Bois

Reputation: 1331

The mysterious behaviour of __callStatic method

SO question Weird behaviour with triggering __callStatic() from non-static method is great because it explains the weird behaviour with the __callStatic not being called from within the class itself (Note that I don't see this behaviour in 5.3.3 but in 5.3.8 and 5.3.12). It seems that the __callStatic can only be invoked from outside the class. That's now a fact. But what do I do if I really want the __callStatic to be called from within my class? What syntax should I use to get over the issue?

Upvotes: 1

Views: 238

Answers (2)

Fabian Schmengler
Fabian Schmengler

Reputation: 24551

It does not have to be from outside the class, just not from object context (i.e. where $this is an instance of the class). So you can wrap this call in a static method, for example:

class TestCallStatic
{
    public function __call($func, $args)
    {
        echo "__call($func)";
    }

    public static function __callStatic($func, $args)
    {
        echo "__callStatic($func)";
    }

    public function test()
    {
        self::_test();
    }
    protected static function _test()
    {
        self::i_am_static();
    }
}

$test = new TestCallStatic();
$test->test();

Output:

__callStatic(i_am_static)

Upvotes: 3

user217782
user217782

Reputation:

You could abstract the functionality to another method like Class::magicCall($method, $args) and call that from within __callStatic(). That way you can also access that functionality by simply calling Class::magicCall() directly.

Upvotes: 0

Related Questions