dongtan6543 2014-12-10 03:04
浏览 22
已采纳

PHP5 - 通过字符串启动一个类 - 两种不同的方式

As I am learning how PHP OOP works, I stumbled upon the following confusion.

class Foo {

    static function baz() {
        echo 'works';
    }

}

# 1
$a = 'Foo';
$a::baz();

# 2
Foo::baz();

PHP manual states that since 5.3.0, it is possible to reference a static class via a string (http://php.net/manual/en/language.oop5.static.php)

What I don't understand is, what is the different between #1 and #2? Aren't they technically the same since both are calling a static function without initiating a class? Where can #1 be applied in practical scenario?

  • 写回答

1条回答 默认 最新

  • dreamy1992 2014-12-10 03:27
    关注

    The difference is in a version. Before PHP5.3 you cannot use static methods with variable.

    Also, second one 'hide' using of a class. Your IDE could not find class usage.

    Also you could use object to call static methods.

    class Foo {
        static function baz() {
            echo 'works';
        }
    }
    
    eval(
    '$a = "Foo";
    $a::baz();');
    
    eval(
    '$a = new Foo();
    $a::baz();');
    
    eval(
    'Foo::baz();');
    

    http://3v4l.org/WOK44

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 win10权限管理,限制普通用户使用删除功能
  • ¥15 minnio内存占用过大,内存没被回收(Windows环境)
  • ¥65 抖音咸鱼付款链接转码支付宝
  • ¥15 ubuntu22.04上安装ursim-3.15.8.106339遇到的问题
  • ¥15 求螺旋焊缝的图像处理
  • ¥15 blast算法(相关搜索:数据库)
  • ¥15 请问有人会紧聚焦相关的matlab知识嘛?
  • ¥15 网络通信安全解决方案
  • ¥50 yalmip+Gurobi
  • ¥20 win10修改放大文本以及缩放与布局后蓝屏无法正常进入桌面