PHP在调用静态方法时使用变量 [英] PHP Using a variable when calling a static method
问题描述
我有三个类,每个类都有一个名为"create"的静态函数. 我想根据表单的输出动态调用适当的函数,但是语法有点麻烦.反正有执行此操作吗?
I have three classes that all have a static function called 'create'. I would like to call the appropriate function dynamically based on the output from a form, but am having a little trouble with the syntax. Is there anyway to perform this?
$class = $_POST['class'];
$class::create();
任何建议将不胜感激.
谢谢.
推荐答案
如果使用的是PHP 5.2,则可以使用 call_user_func
(或 call_user_func_array
):
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';
}
}
将帮助您:
Hello, A
您在问题中使用的那种语法只有在PHP> = 5.3时才可能;请参阅静态关键字的手册页:
The kind of syntax you were using in your question is only possible with PHP >= 5.3 ; see the manual page of Static Keyword, about that :
从PHP 5.3.0开始,可以 使用变量引用类. 变量的值不能为 关键字(例如,自我,父母和 静态).
As of PHP 5.3.0, it's possible to reference the class using a variable. The variable's value can not be a keyword (e.g. self, parent and static).
这篇关于PHP在调用静态方法时使用变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!