-2

I'm reading a book of php and found this code:

class Employee {
        static public $NextID = 1;
        public $ID;

        public function _ _construct( ) {
                $this->ID = self::$NextID++;
        }

        public function NextID( ) {
                return self::$NextID;
        }
}

why here is used self::$NextID++; can I use like this:

$this-ID = $this->$NextID++;
Bhojendra Rauniyar
  • 83,432
  • 35
  • 168
  • 231

2 Answers2

1

Because in php you have to reference static functions with self.

There was also an explanation on stackoverflow already: see here

Community
  • 1
  • 1
sHentschel
  • 155
  • 6
0

When a class is called statically ie. ClassName::someMethod(), there is no "instance" of the class.

Since $this refers to the instance of the class, $this will not exist when your class is used statically. (so $this will only be available when you created an object of your class by using $var = new ClassName())

self refers to the class (not the object) so in static classes you can use self::.. to refer to properties or methods within the class.

Damien Overeem
  • 4,487
  • 4
  • 36
  • 55