PHP在静态构造函数中增加一个数字


php increment a number in static constructor

我需要在类的构造函数中增加一个数字,而不调用静态函数。我的代码如下:

class Addup {
static public $num;
function __construct($num) {
  echo 'My number is==>' . $num;
  static::$num++;
  }
}
$inc = new Addup();//instantiated an object
echo '<br>';
echo $inc::$num;//should be 2, but still 1, should it be $inc = new     Addup() or $inc->addup() implemented in my class?
echo '<br>';
echo $inc::$num;//should be 3, but still 1
echo '<br>';
echo $inc::$num;//should be 4, but still 1

欢迎大家多多指教,谢谢

UPD做了如下重构:

$inc = new Increment();//My number is==>2
echo '<br>';
$inc = new Increment();//My number is==>3
echo '<br>';
$inc = new Increment();//My number is==>4
echo '<br>';
$inc = new Increment();//My number is==>5

这是唯一的方法,做到没有调用函数在一个类吗?

静态属性意味着静态属性的值在类的多个实例化中是相同的。

这可能比您的示例

更好地演示代码发生了什么。

旁注:你传递的参数对任何东西都没有影响,也没有任何作用

<?php
class Addup {
    static public $num;
    function __construct() {
        static::$num++;
    }
}
$inc1 = new Addup();   // calls the constructor therefore +1
echo PHP_EOL;
echo $inc1::$num; // 1
$inc2 = new Addup();   // calls the constructor therefore +1
echo PHP_EOL;
echo $inc2::$num; // 2
$inc3 = new Addup();   // calls the constructor therefore +1
echo PHP_EOL;
echo $inc3::$num; // 3
// now if you look at $inc1::$num; after instantiating inc2 and inc3
echo PHP_EOL;
echo $inc1::$num; // NOT 1 but whatever it was last incremented to i.e. 3