What's the difference between :: (double colon) and -> (arrow) in PHP?

前端 未结 6 1248
隐瞒了意图╮
隐瞒了意图╮ 2020-11-22 16:54

There are two distinct ways to access methods in PHP, but what\'s the difference?

$response->setParameter(\'foo\', \'bar\');

and

6条回答
  •  天涯浪人
    2020-11-22 17:45

    :: is used in static context, ie. when some method or property is declared as static:

    class Math {
        public static function sin($angle) {
            return ...;
        }
    }
    
    $result = Math::sin(123);
    

    Also, the :: operator (the Scope Resolution Operator, a.k.a Paamayim Nekudotayim) is used in dynamic context when you invoke a method/property of a parent class:

    class Rectangle {
         protected $x, $y;
    
         public function __construct($x, $y) {
             $this->x = $x;
             $this->y = $y;
         }
    }
    
    class Square extends Rectangle {
        public function __construct($x) {
            parent::__construct($x, $x);
        }
    }
    

    -> is used in dynamic context, ie. when you deal with some instance of some class:

    class Hello {
        public function say() {
           echo 'hello!';
        }
    }
    
    $h = new Hello();
    $h->say();
    

    By the way: I don't think that using Symfony is a good idea when you don't have any OOP experience.

提交回复
热议问题