Bhojendra Rauniyar
Bhojendra Rauniyar

Reputation: 85545

Why is my constructor working incorrectly?

Here is the example of code:

class Empolyee{
    static public $nextID = 1;
    public $ID;
    public function __construct(){
        $this->ID = self::$nextID++;
    }
    public function NextID(){
        return self::$nextID;
    }
}

$bob = new Employee;
$jan = new Employee;
$simon = new Employee;

print $bob->ID . "\n";
print $jan->ID . "\n";
print $simon->ID . "\n";
print Employee::$nextID . "\n";
print Eployee::NextID() . "\n";

The above code returns 1,2,3,4,4 but for this I'm misunderstanding that it should return 2,3,4,5,5 because within the class Employee the value of $nextID is 1 then when creating a new object the contructor function is automatically initiated as if the value is increased by 1. So when creating first object, the $bob, here it should return 1+1= 2. Please make my concept clear about this. Thanks.

Upvotes: 1

Views: 61

Answers (2)

Hongzheng
Hongzheng

Reputation: 385

ref: http://www.php.net/manual/en/language.operators.increment.php

Example     Name            Effect
++$a        Pre-increment   Increments $a by one, then returns $a.
$a++        Post-increment  Returns $a, then increments $a by one.

So in your case, it always return the current $nextID before adding it by 1.

Upvotes: 1

Preet Sangha
Preet Sangha

Reputation: 65506

$this->ID = self::$nextID++; is POST INCREMENT

Set the $ID of $bob to 1 and then increments $nextID to 2 (the increment is AFTER (POST) the assignment completes - ie. it's the same as:

$this->ID = self::$nextID;
self::$nextID = self::$nextID + 1

This cycle them repeats for @jan and then $simon

If you want ID to increase before the assignment use PRE INCREMENT

$this->ID = ++self::$nextID; 

Upvotes: 0

Related Questions