简体   繁体   中英

PHP call a static method of a class by class name

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM