dongyuchen0214 2011-10-30 11:31
浏览 69
已采纳

PHP:调用没有类名的静态方法

I have simllar question like here: static-method-invocation, but in PHP. Simply, I want have class like this:

static class ClassName{
   static public function methodName(){
         //blah blah blah
   }
}

and I want to call member method without name od class like this:

require_once(ClassName.php);

methodName();

Is it possible in PHP? Thanks for your answers!

  • 写回答

2条回答 默认 最新

  • duanjie6912 2011-10-30 11:48
    关注

    You can not do what you're looking for. The example call you give:

    methodName();
    

    Is calling a global function. Even static class functions are global as well, they always need the class-name to be called:

    ClassName::methodName();
    

    This calls the global static class function you've created in the include file.

    I can only guess what you'd like to achieve, maybe you can benefit from the feature that includes can return values:

    static class ClassName{
       static public function methodName(){
             //blah blah blah
       }
    }
    return 'ClassName';
    

    Including:

    $className = require_once(ClassName.php);
    $className::methodName();
    

    However this won't work with reguire_once when the file has been loaded earlier.

    You can write a wrapper function to require_once files, store their return value into a global context array that keeps these values based on the file-name of the include.

    Keep in mind that the java language differs from PHP. The equivalent to the java static function would be the global function in PHP:

    function methodName(){
        //blah blah blah
    }
    

    Including:

    require_once(ClassName.php);
    methodName();
    

    That's the PHP equivalent.

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

报告相同问题?

悬赏问题

  • ¥15 使用sql语句实现下面两个实验(需要代码和运行结果截图)
  • ¥15 正则化逻辑回归损失函数
  • ¥20 用web解决,要给我一个完整的网页,符合上述的要求
  • ¥20 求个sql代码和结果的图 两道题
  • ¥15 银河麒麟操作系统无法使用U盘
  • ¥100 寻找:光电二极管电路设计服务
  • ¥15 YOLOv5改进后的结构图
  • ¥15 全志v3s怎么设置高速时钟,使用的荔枝派zero开发板,串口2需要921600的波特率
  • ¥15 关于#单片机#的问题:Lora通讯模块hc-14电路图求内部原理图
  • ¥50 esp32 wroom 32e 芯片解锁