繁体   English   中英

从__callStatic调用私有静态方法

[英]Calling a private static method from __callStatic

我想使用__callStatic作为预处理器来调用静态方法。 我的想法是使方法私有,以便每个静态调用都转发到__callStatic。 然后,我可以使用它来做一些事情,然后调用该方法。 但似乎不可能。 这是一个例子:

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');

也许有人正在解决方案:-)

这也有效

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');

原始文件的第一个问题是使方法私有。 私有方法仅在当前类的范围内(在本例中为B :: test()),但是,该方法是从A :: __ callStatic()调用的,因此不在范围之内。

第二个问题是对self的使用::尽管我不能提供足够的解释来说明为什么我害怕(也许更精通细微差别的人可能会有所启发?),但是用static关键字代替self可以起作用。

这有效

    <?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');

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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