私有计数器静态变量在从派生类实例化时增加

时间:2015-02-13 12:19:31

标签: php oop

当$ 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

3 个答案:

答案 0 :(得分:0)

你的类counter2有一个隐式构造函数,它调用超类的构造函数,它可以访问私有变量并在调用它时递增它。

答案 1 :(得分:0)

答案非常简单,您也可以在手册中找到它:http://php.net/manual/en/language.oop5.decon.php

从那里引用:

  

注意:如果子类定义了构造函数,则不会隐式调用父构造函数

所以如果你不希望它递增,你可以简单地声明一个这样的空构造函数:

class counter2 extends counter{
    public function __construct() {}
}

答案 2 :(得分:0)

你有一个计数器类的默认构造函数。你需要增量静态计数器。如你所知,静态变量保留了内存(值)。这就是为什么它的增量。其他明智的你可以简单地使用私有不要让它静止。

private or protected count = 0;

或者如果还有,请告诉我你想要的输出..

由于

相关问题