16

Possible Duplicate:
In PHP, whats the difference between :: and ->?

In PHP, what is the main difference of while calling a function() inside a class with arrow -> and Scope Resolution Operator :: ?

For more clearance, the difference between:

$name = $foo->getName();
$name = $foo::getName();

What is the main profit of Scope Resolution Operator :: ?

Community
  • 1
  • 1
夏期劇場
  • 17,821
  • 44
  • 135
  • 217

3 Answers3

22
$name = $foo->getName();

This will invoke a member or static function of the object $foo, while

$name = $foo::getName();

will invoke a static function of the class of $foo. The 'profit', if you wanna call it that, of using :: is being able to access static members of a class without the need for an object instance of such class. That is,

$name = ClassOfFoo::getName();
K-ballo
  • 80,396
  • 20
  • 159
  • 169
  • `::` can accessible to `static` members of class??? woah! Enough profit so! :D Thanks buddy, K-ballo – 夏期劇場 Sep 23 '11 at 05:31
  • If `::` can access to the `static` member, so what is the beauty of `static`?? I think this is just an un-structured way in PHP :( – 夏期劇場 Sep 23 '11 at 18:48
  • You seem to be confusing `static` with something else, in all languages there are ways to access static (public) members of a class. – K-ballo Sep 23 '11 at 19:30
  • much more detailed answer regarding this topic can be found here: https://stackoverflow.com/a/17027307/4126723 – J Z Aug 09 '18 at 12:49
9
  • -> is called to access a method of an instance (or a variable of an instanciated object)
  • :: is used to access static functions of an uninstanced object
genesis
  • 50,477
  • 20
  • 96
  • 125
1

They are for different function types. -> is always used on an object for static and non-static methods (though I don't think it's good practice use -> for static methods). :: is only used for static methods and can be used on objects (as of PHP 5.3) and more importantly classes.

<?php

class aClass {
    static function aStaticMethod() {}
    function aNormalMethod() {}
}

$obj = new aClass();
$obj->aNormalMethod(); //allowed
$obj->aStaticMethod(); //allowed
$obj::aStaticMethod(); //allowed as of PHP 5.3
$class_name = get_class( $obj );
$class_name::aStaticMethod(); //long hand for $obj::aStaticMethod()
aClass::aStaticMethod(); //allowed
//aClass::aNormalMethod(); //not allowed
//aClass->aStaticMethod(); //not allowed
//aClass->aNormalMethod(); //not allowed
Kendall Hopkins
  • 43,213
  • 17
  • 66
  • 89