PHP Using a variable when calling a static method

I have three classes that have a static function called create. I would like to call the corresponding function dynamically based on the output from the form, but I have a little syntax problem. Is there any way to accomplish this?

$class = $_POST['class']; $class::create(); 

Any advice is appreciated.

Thanks.

+4
source share
5 answers

If you are working with PHP 5.2, you can use call_user_func (or call_user_func_array ):

 $className = 'A'; call_user_func(array($className, 'method')); class A { public static function method() { echo 'Hello, A'; } } 

You'll get:

 Hello, A 


The type of syntax you used in your question is only possible with PHP> = 5.3; see the static keyword manual page about which:

Starting with PHP 5.3.0, it is possible to reference the class using a variable. The value of a variable cannot be a keyword (for example, self, parent, and static).

+8
source

You have work with PHP 5.3 .

ps. You should consider clearing $ _POST ['class'], since you cannot be sure what will be in it.

+2
source

use call_user_func

Here is an example from php.net

 class myclass { static function say_hello() { echo "Hello!\n"; } } $classname = "myclass"; call_user_func(array($classname, 'say_hello')); call_user_func($classname .'::say_hello'); // As of 5.2.3 $myobject = new myclass(); call_user_func(array($myobject, 'say_hello')); 
+1
source

I believe that this can only be done with PHP 5.3.0. Check this page and search for $classname::$my_static to see an example.

0
source

I may not understand what you want, but what about this?

 switch ($_POST['ClassType']) { case "Class1": $class1::create(); break; case "Class2": $class2::create(); break; // etc. } 

If this does not work, you should study EVAL (dangerous, be careful.)

-2
source

All Articles