有没有办法用PHP来做到这一点?静态方法


Is there a way to perform this with PHP? Static methods

看起来不可能做这样的事情:

class Service
{
    public function get($argument1, $argument2)
    {
        echo "Arguments: $argument1, $argument2.";
    }
}
class Main
{
    public function __callStatic($method, $arguments)
    {
        $method = "get".ucfirst($method);
        $arguments = implode(", ", $arguments);
        $object = self::$method;
        return $object->get($arguments);
    }
    public static function getService()
    {
        return new Service;
    }
}
$main = new Main;
$main::Service("1", "2"); // Should output 'Arguments: 1, 2.'

问题是自我混乱的一切,这是可能的。

使用 self:

:$variable, self 这个我们在主上下文中有一个变量。

$object = 自我也不起作用。

$object = 克隆自我也不起作用。

定义("方法", $method);self::method将不起作用,因为self thinks是一个类常量属性。

不能使用。

有没有办法做到这一点?

只需将原始$arguments直接传递给call_user_func_array

return call_user_func_array(array($object, "get"), $arguments);

然后,只需对Main进行静态调用:

Main::service("1", "2");

在这里看到它的实际效果:http://codepad.viper-7.com/phhqy6