dongtu4028 2009-10-26 19:33
浏览 252
已采纳

PHP在调用静态方法时使用变量

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();

Any advice would be greatly appreciated.

Thanks.

  • 写回答

5条回答 默认 最新

  • drbae3964 2009-10-26 19:39
    关注

    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';
        }
    }
    

    Will get you :

    Hello, A
    


    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 :

    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).

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(4条)

报告相同问题?

悬赏问题

  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料