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

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

本文介绍了不能从类中将静态方法作为变量名调用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm using php 5.2.6. I have a strategy pattern, and the strategies have a static method. In the class that actually implements one of the strategies, it gets the name of the strategy class to instantiate. However, I wanted to call one of the static methods before instantiation, like this:

$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中可以使用吗?

Would this work in 5.3?

推荐答案

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

Yes. That syntax was introduced in 5.3

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

To workaround for <= 5.2, you can use 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));

但要注意的是,您尝试执行的操作并没有任何意义...

But on another note, what you're trying to do doesn't really make sense...

为什么将它作为静态函数?无论如何,您在implementation中的构造函数都期望有一个对象(这就是strategyInterface $strategy所寻找的).传递字符串不起作用,因为字符串不实现接口.因此,我要做的是使接口变为非静态,然后执行以下操作:

Why have it as a static function? Your constructor in implementation is expecting an object anyway (that's what strategyInterface $strategy is looking for). Passing a string won't work, since strings don't implement interfaces. So what I would do, is make the interface non-static, and then do something like:

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

然后,在构造函数中:

$strFormat = $strategy->getFormatString();

或者,如果您确实仍然希望该方法是静态的,则可以执行以下操作:

Or, if you really still want that method to be static you could do:

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

哦,并且= & new synax是已弃用(并且不做您认为会做的事情.

Oh, and = & new synax is deprecated (and doesn't do what you think it does anyway).

这篇关于不能从类中将静态方法作为变量名调用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 06:17