$count静态属性在声明为private时是如何递增的,当我实例化派生类(counter2)时,它仍然在递增?我不知道当我在这里实例化一个派生类时,它是如何递增的
class counter{
/*** our count variable ***/
private static $count = 0;
/*Constructor*/
function __construct() {
self::$count++;
}
/*get the current count
* @access public
* @return int*/
public static function getCount() {
return self::$count;
}
} /*** end of class ***/
//extend the counter class
class counter2 extends counter{
}
/*** create a new instance ***/
$count = new counter();
/*** get the count ***/
echo counter::getCount() . '<br />';
/*** create another instance ***/
$next = new counter();
/*** echo the new count ***/
echo counter::getCount().'<br />';
/*** and a third instance ***/
$third = new counter;
echo counter::getCount().'<br />';
$count2=new counter2();
echo counter2::getCount();
输出:1.2.3.4
类counter2有一个隐式构造函数,它调用其超类的构造函数,该构造函数可以访问私有变量,并在调用时递增。
答案很简单,您也可以在手册中找到:http://php.net/manual/en/language.oop5.decon.php
还有一句话:
注意:如果子类定义构造函数,则不会隐式调用父构造函数
因此,如果您不希望它递增,您可以简单地声明一个空构造函数,如下所示:
class counter2 extends counter{
public function __construct() {}
}
您有一个计数器类的默认构造函数。。并且你想要增量静态计数器。正如您所知,静态变量会保留内存(值),这就是它递增的原因。其他明智的做法是,你可以简单地使用private,不要让它成为静态的。
private or protected count = 0;
否则请告诉我你想要什么输出。。
感谢