【问题标题】:Is there a way to perform this with PHP? Static methods有没有办法用 PHP 执行此操作?静态方法
【发布时间】:2013-09-16 02:19:05
【问题描述】:

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

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 这个我们在 Main 上下文中有一个变量。

$object = self 也不行。

$object = clone self don't' work too.

define("方法", $method); self::method 不起作用,因为 self 认为是类常量属性。

这个不能用。

有没有办法做到这一点?

【问题讨论】:

    标签: php class methods static self


    【解决方案1】:

    只需将原来的$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

    【讨论】:

    • Joseph,看起来是一个非常有趣的解决方案。但我还没有完全理解。你能为我写下所有的 * __callStatic* 吗?我想知道如果主要问题是我无法使用语句 $object = self::$method;.
    • @GarouDan - 你得叫它$object = self::$method(): codepad.viper-7.com/phhqy6
    猜你喜欢
    • 1970-01-01
    • 2013-04-01
    • 1970-01-01
    • 2013-01-29
    • 2013-10-10
    • 2013-11-28
    • 2014-07-16
    • 2013-05-12
    • 2019-09-07
    相关资源
    最近更新 更多