PHP Classes: when to use :: vs. ->?

后端 未结 7 2214
暗喜
暗喜 2020-12-04 19:36

I understand that there are two ways to access a PHP class - \"::\" and \"->\". Sometime one seems to work for me, while the other doesn\'t, and I don\'t understand why.

7条回答
  •  情话喂你
    2020-12-04 20:11

    It should also be noted that every static function can also be called using an instance of the class but not the other way around.

    So this works:

    class Foo
    {
      public static function bar(){}
    }
    
    $f = new Foo();
    $f->bar(); //works
    Foo::bar(); //works
    

    And this doesn't:

    class Foo
    {
      protected $test="fddf";
      public function bar(){ echo $this->test; }
    }
    
    $f = new Foo();
    $f->bar(); //works
    Foo::bar(); //fails because $this->test can't be accessed from a static call
    

    Of course you should restrict yourself to calling static methods in a static way, because instantiating an instance not only costs memory but also doesn't make much sense.

    This explanation was mainly to illustrate why it worked for you some of the times.

提交回复
热议问题