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

后端 未结 7 2215
暗喜
暗喜 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:12

    Simply put, :: is for class-level properties, and -> is for object-level properties.

    If the property belongs to the class, use ::

    If the property belongs to an instance of the class, use ->

    class Tester
    {
      public $foo;
      const BLAH;
    
      public static function bar(){}
    }
    
    $t = new Tester;
    $t->foo;
    Tester::bar();
    Tester::BLAH;
    

提交回复
热议问题