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

前端 未结 6 1252
隐瞒了意图╮
隐瞒了意图╮ 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:27

    Actually by this symbol we can call a class method that is static and not be dependent on other initialization...

    class Test {
    
        public $name;
    
        public function __construct() {
            $this->name = 'Mrinmoy Ghoshal';
        }
    
        public static function doWrite($name) {
            print 'Hello '.$name;
        }
    
        public function write() {
            print $this->name;
        }
    }
    

    Here the doWrite() function is not dependent on any other method or variable, and it is a static method. That's why we can call this method by this operator without initializing the object of this class.

    Test::doWrite('Mrinmoy'); // Output: Hello Mrinmoy.

    But if you want to call the write method in this way, it will generate an error because it is dependent on initialization.

提交回复
热议问题