我有三个类,它们都有一个名为“create”的静态函数。 我想根据表单的输出动态调用适当的函数,但语法有点问题。无论如何执行此操作?
$class = $_POST['class'];
$class::create();
如有任何建议,我们将不胜感激。
谢谢。
最佳答案
如果您使用的是 PHP 5.2,则可以使用 call_user_func
(或 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 ;请参阅 Static Keyword 的手册页,关于那个:
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 在调用静态方法时使用变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1626870/