简体   繁体   中英

Calling a private static method from __callStatic

I want to use __callStatic as a preProcessor for calling static methods. My idea is to make the methods private so every static call is forwarded to __callStatic. Then I could use this to do some stuff and call the method then. But it seems not possible. Here is an example:

class A {

    public static function __callStatic($name, $params) {
        var_dump($name);

        // TODO call the private function from class B here

        //call_user_func_array('self::' . $name, $params); //infinite loop

    }

}

class B extends A {

    private static function test($bar) {
        echo $bar;
    }

}

B::test('foo');

Perhaps somebody is having a solution :-)

This works too

class A 
{
    public static function __callStatic($method, $params)
    {
        return call_user_func_array('static::'.$method, $params);
    }
}
class B extends A
{
    protected static function test($value)
    {
        echo $value;
    }
}
B::test('foo');

The first problem with your original is making your methods private. Private methods are only in scope for current class (in this case B::test()), however, the method is called from A::__callStatic() and so is out of scope.

The second issue is use of self:: although I can't offer an adequate explanation why I'm afraid (perhaps someone more versed in the nuances might shed some light?), but replacing self with the static keyword works.

This works

    <?php
/**
 * Created by JetBrains PhpStorm.
 * User: ckoch
 * Date: 19.05.12
 * Time: 10:43
 * To change this template use File | Settings | File Templates.
 */

class A {

    public static function __callStatic($name, $params) {
        var_dump($name);

        // TODO call the private function from class B here

        //call_user_func_array('self::' . $name, $params); //infinite loop

        //forward_static_call_array(array(self, $name), $params); // loops too

        $method = new ReflectionMethod(get_called_class(), $name);
        $method->setAccessible(true);
        $method->invokeArgs(null, $params);

    }

}

class B extends A {

    private static function test($bar) {
        var_dump($bar);
    }

}

B::test('foo');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM