user834780
user834780

Reputation: 51

What is the difference between accessing a class method via -> and via ::?

What is the difference between accessing a class method via -> and via ::?

Upvotes: 5

Views: 1952

Answers (4)

oezi
oezi

Reputation: 51817

:: is used for accessing static methods or attributes, so you don't have to instantiate an object of the containing class.

-> is used for accessing methods or attributes of instantiated objects.

Upvotes: 4

Jordan Arsenault
Jordan Arsenault

Reputation: 7428

What Francois said is correct. The :: operator is called the Scope Resolution Operator.... and (believe it or not) known as paamayim-nekudotayim. It is used when accessing static, constant, and overridden members of a class. I stress class because it is not used on specific objects. You can think of the scope resolution operator as meta to the class itself; it acts on itself and its parents. (Think about it, class constants don't belong to any specific object so you wouldn't use ->

Which brings us to what is ->? It's used to operate of objects and not classes. When you create a specific object you can access it's properties and methods using this operator. For example:

$john = new User(); //create the object
$john->age = 10; //accessing an object property
$age = $john->getAge(); //accessing an object method

Upvotes: 1

Brad Christie
Brad Christie

Reputation: 101614

Using the -> means your accessing methods based on an instance (it retains state of the object, such as private/public variables set).

The :: is a static method, meaning it has no baring if the object has or has not been initialized, but these methods pertain to this object.


Picture the following:

class Mustang
{
  var $gallons = 12; // gallons

  public function getFuel()
  {
    return $this->gallons;
  }

  public static function getEngine()
  {
    return "V8";
  }
}

$mustang = new Mustang(); // creating an instance

echo $mustang->getFuel(); // retrieve the fuel (instance, _this_ mustang)

echo Mustang::getEngine(); // echo a stat about Mustangs in general (static)

If you had an instance of a "Mustang", each instance could (hypothetically) have a specific amount of fuel to it (this is instance based, and would be accessible using ->).

If you wanted something that still pertains to the mustang, but has no baring on the specific instance itself, you would refer to a static method (in this case all mustangs have a V8 in this case, symbolic of ::).

Upvotes: 2

Francois Deschenes
Francois Deschenes

Reputation: 24989

The -> is for accessing properties and methods of instantiated objects. The :: is to access static methods, constants or overridden methods.

For more information:

Upvotes: 6

Related Questions