php - Can't call static method from class as variable name? -
i'm using php 5.2.6. have strategy pattern, , strategies have static method. in class implements 1 of strategies, gets name of strategy class instantiate. however, wanted call 1 of static methods before instantiation, this:
$strnameofstrategyclass::staticmethod(); but gives 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 suhosin-patch 0.9.6.2 (cli) (built: aug 4 2010 03:25:57) would work in 5.3?
yes. syntax introduced in 5.3
to workaround <= 5.2, can use call_user_func:
call_user_func(array($classname, $funcname), $arg1, $arg2, $arg3); or call_user_func_array:
call_user_func_array(array($classname, $funcname), array($arg1, $arg2, $arg3)); but on note, you're trying doesn't make sense...
why have static function? constructor in implementation expecting object anyway (that's strategyinterface $strategy looking for). passing string won't work, since strings don't implement interfaces. do, make interface non-static, , like:
$strategy = new strategyb(); $implementation = new implementation($strategy); then, in constructor:
$strformat = $strategy->getformatstring(); or, if still want method static do:
$strformat = call_user_func(array(get_class($strategy), 'getformatstring')); oh, , = & new synax deprecated (and doesn't think anyway).
Comments
Post a Comment