为什么我的构造函数工作不正确


Why is my constructor working incorrectly?

以下是代码示例:

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";

上面的代码返回1,2,3,4,4,但为此我误解了它应该返回2,3,4,5,5,因为在类Employee中,$nextID的值是1,然后在创建新对象时,构造函数函数会自动启动,就好像值被增加1一样。因此,在创建第一个对象$bob时,这里它应该返回1+1=2。请阐明我的概念。谢谢

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.

因此,在您的情况下,它总是返回当前的$nextID,然后再加1。

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

将$bob的$ID设置为1,然后将$nextID增量为2(增量为AFTER(POST)分配完成后,即与:相同

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

这个循环他们重复@jan然后$simon

如果你想在分配前增加ID,请使用PRE INCREMENT

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