douzong5835 2009-11-09 13:22 采纳率: 100%
浏览 25
已采纳

为什么self :: function()和$ self-> variable或self :: $ variable即使有$ this-> function()和$ this-> variable(PHP)?

I'm confused about these two keywords and the way to use them in PHP5. I think that "this" is used for instanced objects (not static) while "self" is referring to the object itself, not an instance of it and thus used within static objects. Right?

Now, I believe that the correct use inside a class's static method to call another static variable/method is the following:

self::doSomething();
self::$testVar;

That's true?

However, the following also seems to be possible:

$self->testVar;

Yet, $testVar is static. Why is that?

Also, why is $ used infront of self sometimes and sometimes not, and same question for "this" keyword?

  • 写回答

2条回答 默认 最新

  • douze1332 2009-11-09 13:26
    关注

    You're right, self is for static self-references while $this is for instantiated ones. self and $this might appear to work everywhere but consider this:

    class A
    {
      public static function foo()
      {
        $this->bar();
      }
    
      public static function bar()
      {
        echo 'foobar!';
      }
    }
    
    A::foo(); // Fatal error: Using $this when not in object context
    

    This results in a fatal error because foo() was called statically. It's best to take some time and use them appropriately rather than always using one or the other.

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

报告相同问题?

悬赏问题

  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料