user3510768
user3510768

Reputation: 135

Call method non-static with static in PHP

i have code look like this:

abstract class Object
{
    public static function __callStatic($name, $parameters)
    {
        $object = get_called_class();
        $object = new $object;
        if (method_exists($object, $name)) {
            return call_user_func_array(array($object, $name), $parameters);
        }
    }
}

class Log extends Object
{
    public function message($message)
    {
        echo 'Log: '.$message.'.<br>';
    }
}

now, i call:

Log::message('test');

this's result:

Strict standards: Non-static method Log::message() should not be called statically...

Log: test.

somebody can help me?

Upvotes: 2

Views: 382

Answers (2)

Alma Do
Alma Do

Reputation: 37365

That's because __callStatic() will be triggered only for non-existent methods while your message() method exists and it's non-static.

E.g Log::foo('test'); won't trigger this message since there's no such method.

You're checking your method on existence inside __callStatic() and this has no sense: if __callStatic() was called, it's a call for non-existent method. Thus, condition will always be false and useless.

This may seems odd (because you may wish to call static method as non-static and create instance inside __callStatic()) - but from point of visibility, static and non-static methods are same: thus, if method exists as static it will also be visible as non-static.

Upvotes: 1

cfv1000
cfv1000

Reputation: 463

__callStatic will work only if your method does not exist. Rename your method from "message" to "messageStatic" and change __callStatic method:

 if (method_exists($object, $name.'Static')) {
    return call_user_func_array(array($object, $name.'Static'), $parameters);
}

Upvotes: 3

Related Questions