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

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

    Php can be confusing in this regard you should read this.

    What's also confusing is that you can call non static functions with the :: symbol. This is very strange when you come from Java. And it certainly surprised me when I first saw it.

    For example:

    class Car
    {
        public $name = "Herbie 
    "; public function drive() { echo "driving
    "; } public static function gas() { echo "pedal to the metal
    "; } } Car::drive(); //will work Car::gas(); //will work $car = new Car(); $car->drive(); // will work $car->gas(); //will work echo $car->name; // will work echo Car::$name; // wont work error

    As you can see static is very loose in php. And you can call any function with both the -> and the :: symbols. But there is a difference when you call with :: there is no $this reference to an instance. See example #1 in the manual.

提交回复
热议问题