-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++;
0

2 Answers 2

1

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

There was also an explanation on stackoverflow already: see here

Sign up to request clarification or add additional context in comments.

1 Comment

Also note that it is valid to call static methods with $this in the same class.
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.

1 Comment

Its not $self is just self, or static

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.