dongyuchen0214 2011-10-30 03: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 03: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 IBMP550小型机使用串口登录操作系统
  • ¥15 关于#python#的问题:现已知七自由度机器人的DH参数,利用DH参数求解机器人的逆运动学解目前使用的PSO算法
  • ¥15 发那科机器人与设备通讯配置
  • ¥15 Linux环境下openssl报错
  • ¥15 我在使用VS编译并执行之后,但是exe程序会报“无法定位程序输入点_kmpc_end_masked于动态链接库exe上“,请问这个问题有什么解决办法吗
  • ¥15 el-select光标位置问题
  • ¥15 单片机 TC277 PWM
  • ¥15 在更新角色衣服索引后,Sprite 并未正确显示更新的效果该如何去解决orz(标签-c#)
  • ¥15 VAE代码如何画混淆矩阵
  • ¥15 求遗传算法GAMS代码
手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部