0

This is a syntax question I think... I have an array of classnames, that I use in a factory to generate objects by object type code:

$array = ['a' => '\namespace\AClass', 'b' => '\namespace\BClass'];

I can instantiate these classes from the string name just fine:

$classname = $array['a'];
return new $classname($arg1, $arg2);

What I am trying to do is call a static method of the class named in the array or string, without having to initialize the object - something like:

$classname = $array['a'];
return $classname::formatArg($arg1);

Obviously, this doesn't work since $classname is a string, so how do I tell PHP I am trying to access the object with that name?

Wige
  • 3,788
  • 8
  • 37
  • 58
  • 3
    Are you sure this doesnt work? If so, you can use call_user_func. It works with class methods, no matter if instance or static. – ToBe Oct 16 '14 at 15:03
  • 1
    What error are you getting? I ran a simple version of this and it works. `class AClass { static function formatArg($arg1) { echo $arg1; } } $array = array('a' => '\AClass', 'b' => '\namespace\BClass'); $arg1 = 'hello'; $classname = $array['a']; var_dump($classname); $classname::formatArg($arg1);` – slapyo Oct 16 '14 at 15:09
  • Huh. I tried it again and it is in fact working. I was getting an unexpected character error in PHP before (maybe a typo?) and the IDE flagged it as an error "Method formatArg not found in string" Thanks for the replies and testing! – Wige Oct 16 '14 at 15:26

1 Answers1

0

Check out this post. How can I call a static method on a variable class?

It look like your code is ok in php 5.3. There's also some ideas how to deal with your problem if you are < 5.3.

Community
  • 1
  • 1
holygrinder
  • 108
  • 7