2

In php, is there any difference between using

$myClass::method()

and

$myClass->method()

What's the reason for the change? (I believe -> has been around longer.)

I could see a point of using :: for methods and -> for properties or vice versa.

hakre
  • 178,314
  • 47
  • 389
  • 754
Teson
  • 6,263
  • 7
  • 41
  • 66

3 Answers3

6

:: is the scope resolution operator, used for accessing static members of classes.

-> is the member operator, used for access members of objects.

Here's an example:

class Car {
   public $mileage, $current_speed, $make, $model, $year;
   public function getCarInformation() {
      $output = 'Mileage: ' . $this->mileage;
      $output = 'Speed: ' . $this->current_speed;
      $output = 'Make: ' . $this->make;
      $output = 'Model: ' . $this->model;
      $output = 'Year: ' . $this->year;
      return $output; 
   }
}

class CarFactory {

    private static $numberOfCars = 0;

    public static function carCount() {
       return self::$numberOfCars;    
    }

    public static function createCar() {
       self::$numberOfCars++; 
       return new Car();
    }

}    

echo CarFactory::carCount(); //0

$car = CarFactory::createCar();

echo CarFactory::carCount(); //1

$car->year = 2010;
$car->mileage = 0;
$car->model = "Corvette";
$car->make = "Chevrolet";

echo $car->getCarInformation();
Jacob Relkin
  • 151,673
  • 29
  • 336
  • 313
  • 1
    PHP calls it a Paamayim Nekudotayim which is so much more natural =) – Rudie Dec 20 '10 at 00:09
  • Ah, thanks. Now, a good reason to bother with static classes? – Teson Dec 20 '10 at 00:16
  • 1
    @user247245: The `static` keyword is necessary for class variables only. For methods you can skip both `static` and `public`, as they change semantics only minusculy. Static classes per se make mostly sense for grouping methods (= poor mans namespace). – mario Dec 20 '10 at 00:21
1

Consider this:

class testClass {
    var $test = 'test';
    
    function method() {
        echo $this->test;
    }
}

$test = new testClass();

$test->method();
testClass::method();

The output will be something like:

test

Fatal error: Using $this when not in object context in ... on line 7

This is because :: makes a static call to a class while -> is used to call methods or properties on a specific instance of a class.

Incidentally, I don't believe you can do $test::method() because PHP will give you a parse error like this:

Parse error: syntax error, unexpected T_PAAMAYIM_NEKUDOTAYIM in ... on line 14

Community
  • 1
  • 1
treeface
  • 12,934
  • 3
  • 48
  • 57
0

:: is also used within a class/object to call its parent, e.g.:

parent::__constructor();

Also if it's called from within an object (so not statically).

Rudie
  • 46,504
  • 37
  • 126
  • 167