php - 不能从类中调用静态方法作为变量名?

标签 php strategy-pattern php-5.2

我使用的是 PHP 5.2.6。我有一个策略模式,策略有一个静态方法。在实际实现其中一种策略的类中,它获取要实例化的策略类的名称。但是,我想在实例化之前调用其中一个静态方法,如下所示:

$strNameOfStrategyClass::staticMethod();

但它给出 T_PAAMAYIM_NEKUDOTAYIM

$> cat test.php

<?

interface strategyInterface {
        public function execute();
        public function getLog();
        public static function getFormatString();
}


class strategyA implements strategyInterface {
        public function execute() {}
        public function getLog() {}
        public static function getFormatString() {}
}

class strategyB implements strategyInterface {
        public function execute() {}
        public function getLog() {}
        public static function getFormatString() {}
}

class implementation {
        public function __construct( strategyInterface $strategy ) {
                $strFormat = $strategy::getFormatString();
        }
}

$objImplementation = & new implementation("strategyB") ;

$> php test.php

Parse error: syntax error, unexpected T_PAAMAYIM_NEKUDOTAYIM in /var/www/test.php on line 24

$> php -v

PHP 5.2.6-1+lenny9 with Suhosin-Patch 0.9.6.2 (cli) (built: Aug  4 2010 03:25:57)

这会在 5.3 中工作吗?

最佳答案

是的。该语法是在 5.3 中引入的

要解决 <= 5.2,您可以使用 call_user_func:

call_user_func(array($className, $funcName), $arg1, $arg2, $arg3);

call_user_func_array:

call_user_func_array(array($className, $funcName), array($arg1, $arg2, $arg3));

但另一方面,您尝试做的事情并没有真正意义...

为什么把它作为一个静态函数? implementation 中的构造函数无论如何都需要一个对象(这就是 strategyInterface $strategy 正在寻找的对象)。传递字符串是行不通的,因为字符串不实现接口(interface)。所以我要做的是使界面成为非静态的,然后做类似的事情:

$strategy = new StrategyB();
$implementation = new Implementation($strategy);

然后,在构造函数中:

$strFormat = $strategy->getFormatString();

或者,如果您真的仍然希望该方法是静态的,您可以这样做:

$strFormat = call_user_func(array(get_class($strategy), 'getFormatString'));

哦,= & new 语法是 deprecated (并且不会按照您的想法去做)。

关于php - 不能从类中调用静态方法作为变量名?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3787957/

相关文章:

PHP:如何使用带有 HTML 净化器的 nl2br() 来保持换行符?

php - 发送 cache-control/expires/pragma 与 404 响应 - 现代浏览器有效/理解?

java - 访问者模式和策略模式有什么区别?

php - PHP 5.2 是否仍会收到安全补丁?

php - 使用 Laravel 插入当前日期时间

使用 .htaccess 处理 PHP 错误并写入 php_error.log 文本文件

java - 如何处理依赖注入(inject)策略

c# - 使用 Unity 的策略模式和依赖注入(inject)

PHP 速记三元运算符 "?:"意外解析错误 ":"

php - mysqli_stmt_get_result 替代 php 5.2.6