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

报告相同问题?

悬赏问题

  • ¥17 pro*C预编译“闪回查询”报错SCN不能识别
  • ¥15 微信会员卡接入微信支付商户号收款
  • ¥15 如何获取烟草零售终端数据
  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向