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 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料