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

后端 未结 7 2219
暗喜
暗喜 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

    When you declare a class, it is by default 'static'. You can access any method in that class using the :: operator, and in any scope. This means if I create a lib class, I can access it wherever I want and it doesn't need to be globaled:

    class lib
    {
        static function foo()
        {
           echo "hi";
        }
    }
    lib::foo(); // prints hi
    

    Now, when you create an instance of this class by using the new keyword, you use -> to access methods and values, because you are referring to that specific instance of the class. You can think of -> as inside of. (Note, you must remove the static keyword) IE:

    class lib
        {
            function foo()
            {
               echo "hi";
            }
        }
    $class = new lib;
    $class->foo(); // I am accessing the foo() method INSIDE of the $class instance of lib.
    

提交回复
热议问题