duancha1065 2010-07-01 10:38
浏览 111
已采纳

为什么PHP中的$ this总是引用当前的类?

I'm a Java developer who has turned to the dark side over the last couple of weeks as I've been trying to write some code in PHP for the first time ever.

Most stuff seems familiar, methods become functions, . becomes ->, variables have a $ in front and you never have any idea what type they are, I get it, but I'm totally stumped by the $this keyword.

I expect $this to call a function in the current class as in java this.myCoolMethod(), but often as I poke through the open source project I'm going through, $this->myCoolMethod() calls a function in a totally different class!

What is happening here? What does '$this' actually mean?

Thank you for any help.

John

  • 写回答

5条回答 默认 最新

  • dtpk04526211 2010-07-01 10:46
    关注

    The reason it sometimes calls a method in a totally different class, is because that class probably extended another class with that method.

    Here is a quick example:

    class bla {
      public function __construct() {}
    
      public function whatwhat() {
        echo "what....";
      }
    }
    
    class lala extends bla {
      public function __construct() {}
    }
    
    
    $lalaObj = new lala();
    
    $lala->whatwhat();
    

    As you can see, even though whatwhat() isn't in the class, it inherits it from the class it extends.

    Hope that helps.

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

报告相同问题?

悬赏问题

  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大
  • ¥15 Oracle中如何从clob类型截取特定字符串后面的字符
  • ¥15 想通过pywinauto自动电机应用程序按钮,但是找不到应用程序按钮信息
  • ¥15 如何在炒股软件中,爬到我想看的日k线
  • ¥15 seatunnel 怎么配置Elasticsearch
  • ¥15 PSCAD安装问题 ERROR: Visual Studio 2013, 2015, 2017 or 2019 is not found in the system.
  • ¥15 (标签-MATLAB|关键词-多址)
  • ¥15 关于#MATLAB#的问题,如何解决?(相关搜索:信噪比,系统容量)
  • ¥500 52810做蓝牙接受端